What is anti-shake, what is throttling

This article is not object-oriented canteen lady’s hand, nor the new era of the wallet can not pull out a few coins lying flat, mainly about javascript common performance optimization scenarios, as well as the difference between anti-shake and throttling.

The scene is introduced into

Take a project the blogger once did for the education industry as an example. Teachers were required to deliver PPT online on their browsers (PPT online H5 drawing board example demonstration), normally no operation button:When an interactive action occurs, exhale the artboard. If you are listening through the mouse mousemove event, set the artboard element to appear as soon as the event is heard. In this way, teachers can perform interactive operations:If the hiding time is 10s, and you move the mouse again at the fifth second, will the artboard disappear after 5s or will it exist? According to normal thinking, as long as you move the mouse, the artboard will disappear after 5s. The time of the artboard should be extended by 10 seconds, so the final execution of hidden artboard only once, that is, even if you keep moving the mouse for 24 hours, the final execution of hidden artboard operation only once, which is a kind of application of anti-shake.

Image stabilization

The above example can lead to the concept of anti-shake: it means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within N seconds, the function execution time will be recalculated.

Attached is a classic anti-shake function:

        let content = document.getElementById('cont')
        content.onmousemove = debounce(move,1000);
        function move() {
            console.log('the mouse move')}function debounce(func, time) {
            let timeout;
            return function () {
                console.log(this)
                let context = this;
                let args = arguments;
                if (timeout) clearTimeout(timeout);
                timeout = setTimeout(() = >{ func.apply(context, args) }, time); }}Copy the code

It looks like this:

For beginners, please think about, and the answer is behind: what does this mean in function, what does apply do, and what role does the timeout variable play?

  • This refers to who called it, such as the DOM element above cont, which can be clearly seen in the red arrow on the console above
  • Apply simply changes the orientation of this and calls the function
  • closure

The throttle

Unlike buffeting, throttling means only executing a function once in n seconds. Unlike buffeting, which may not execute a function once for a long time, throttling only dilutes the execution frequency of the function.

The more classical throttling function is attached:

        let content = document.getElementById('cont')
        content.onmousemove = throttle(move,1000);
        function move() {
            console.log('the mouse move')}function throttle(func, time) {
            let previous = 0;
            return function() {
                let now = Date.now();
                let context = this;
                let args = arguments;
                if(now - previous > time) { func.apply(context, args); previous = now; }}}Copy the code

So the effect is naturally to print the mouse move at a regular time when the mouse move, so I put forward two questions here:

  1. If the mouse moves away from the cont element and then moves over it at a two-second interval, the console will print immediatelyMove the mouse?
  2. If the above code does not move, it will be printed out at an interval of 1sMove the mouseIf not, how to change the code?

diss diss diss

Don’t take off half of your pants.

  1. Yes, now-previous > 1, so move is executed immediately.

2. Will not print, how to implement, directly on the code (of course this is a bit of a trick, ha ha, you also have to consider eliminating the setTimeIntervel timer, above is the timestamp method, the following example using settimeout to write, this is from baidu reference, interested in more research).

let content = document.getElementById('cont') content.onmousemove = setTimeIntervel(throttle(move,1000),1000); Function move() {console.log(' mouse move')} function throttle(func, wait) {let timeout; return function() { let context = this; let args = arguments; if (! timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } }Copy the code

conclusion

In short, you may only perform anti-shake once a generation, but throttling will be performed at a fixed frequency. The functions of anti-shake and throttling above are actually just like some algorithm problems. You don’t need to memorize them, but you need to understand the basic concepts related to closures in the “This”. Thanks for your reading.