Anti-shake and throttling

2021/5/5

Refer to the article

1. Why use the anti – shake throttling

  • When a function is bound to events that fire continuously such as resize, Scroll, mousemove, keyboard input, multiple quick clicks, etc.,

  • If the function is executed every time it is triggered, performance degrades and resource requests become too frequent

  • Like this

    • div{
      	height:150px;
      	line-height:150px;
      	text-align:center;
      	color: #fff;
      	background-color:#ccc;
      	font-size:80px;
      }
      Copy the code
    • <div id="content"></div>
        <script>
          let num = 1;
          const content = document.getElementById('content');
          function count() {
            content.innerHTML = num++;
          };
          content.onmousemove = count;
        </script>
      
      Copy the code
  • As shown above, the count function is executed and the number is increased whenever the mouse moves over the div area.

  • This is where anti-shake and throttling can be used

2. If you

1. What is anti-shake?

  • The so-called shaking prevention means that the function is executed n seconds after the event is triggered. If the event is triggered within N seconds, the function execution time will be recalculated.

2. Use anti-shake

Not an immediate version
  • Effect is the definition of anti-shake

  • let num = 1; const content = document.getElementById('content'); Function count() {this.innerhtml = num++; }; content.onclick = debounce(count,1000); Function debounce(func, wait) {let timeout; return function () { const context = this; const args = [...arguments]; if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args) }, wait); }}Copy the code
  • The code for the stabilization function uses these two lines to get this and the arguments so that debounce eventually returns a function this that points to the DOM element it was called on and still accepts the argument E.

  • The function binds itself to the function this pointer that debounce eventually returns by calling the apply method.

  • Either setTimeout or setInterval, there’s always a return value. The return value is a number that represents the number of timers currently set in the browser.

  • Call the anti – shake function each time it is triggered, if the previous timer (with timer serial number as identifier) is still in place. Clear the previous timer and start a new one.

  • Even if the timer is cleared, its return value will not be cleared. After setting the return value of the timer, it will continue to the back row based on its return value.

Immediate execution version
  • The function will be executed immediately after the event is triggered. The triggering event will not execute the next call of the function within n seconds. The function will be executed again after the event is triggered again in n seconds.

  • Function debounce(func, wait) {let timeout; return function () { const context = this; const args = [...arguments]; if (timeout) clearTimeout(timeout); const callNow = ! timeout; timeout = setTimeout(() => { timeout = null; }, wait); if (callNow) func.apply(context, args); }; }Copy the code
  • The function only fires if callnow is true

  • The first time to call the anti – shake function, there is no timer, trigger function function

  • If the anti-shake function is called again within the time interval, there is already a timer. Even if the timer is cleared, the timer identifier timeout still exists, so the callNow value is false and the function function cannot be triggered

  • After the timer interval expires, execute the code in the timer and set timer identifier timeout to NULL

  • Only after calling the stabilization function will the callNow value be true and trigger the function

merge
  • Add a parameter for judgment

  • Function debounce(func, wait, immediate) {let timeout; return function () { const context = this; const args = [...arguments]; if (timeout) clearTimeout(timeout); if (immediate) { const callNow = ! timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(() => { func.apply(context, args) }, wait); }}}Copy the code

3. The throttle

1. What is throttling?

  • ** By throttling, we mean firing events continuously but executing the function only once in n seconds. ** throttling dilutes the execution frequency of the function.

2. Apply throttling

The time stamp
  • function throttle(func, wait) {
        var previous = 0;
        return function() {
            let now = Date.now();
            let context = this;
            let args = arguments;
            if (now - previous > wait) {
                func.apply(context, args);
                previous = now;
            }
        }
    }
    content.onmousemove = throttle(count,1000);
    Copy the code
  • The timestamp version of the function is triggered at the start of the time period

The timer
  • 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
  • The first time the throttling function is called without a timer, create a timer and fire the function when the interval ends

  • When the throttling function is called again within a time interval, it does not respond because the timer already exists

  • When the interval ends, clear the timer identifier (timeout) and create another timer.

  • Since the timer identifier timeout is set to NULL, the throttling function is invoked again.