current position:Home>Interpretation of throttle debounce source code

Interpretation of throttle debounce source code

2021-08-27 06:40:33 Little star_ ios

Concept

throttle( throttle )

A function can only be executed once in a certain time .

debounce( Shake proof )

After the event is triggered , stay n Can only be executed once after seconds , If in n Seconds to trigger the event , The execution time of the function is recalculated .

Source code learning

throttle The implementation of the

function throttle(delay, callback) {
  let timeoutID;
  let lastExec = 0;
​
  function wrapper() {
    const self = this;
    const elapsed = Number(new Date()) - lastExec;
    const args = arguments;
​
    function exec() {
      lastExec = Number(new Date());
      callback.apply(self, args);
    }
​
    clearTimeout(timeoutID);
​
    if (elapsed > delay) {
      exec();
    } else {
      timeoutID = setTimeout(exec, delay - elapsed);
    }
  }
​
  return wrapper;
}
 Copy code 

The logic of the whole code is very clear , There are only three steps :

  1. Calculate the time elapsed since the most recent function execution  elapsed, And clear the previously set timer .
  2. If the elapsed time is greater than the set time interval  delay, Then execute the function immediately , And update the execution time of the last function .
  3. If the elapsed time is less than the set time interval  delay, Then through the  setTimeout  Set a counter , Let the function  delay - elapsed  Execute after time .

The source code is not difficult to understand , But we need to pay attention to  this  Use :

function throttle(delay, callback) {
    // ...
    function wrapper() {
        const self = this;
        const args = arguments;
        // ...
        
        function exec() {
            // ...
            callback.apply(self, args);
        }
        
    }
}
 Copy code 

In the code above , adopt  self  Variables are temporarily saved  this  Value , Thus in  exec  Function through  callback.apply(self, args)  Pass in the right  this  value , This is done in Closure Related function calls are very common . Because it's right here  this  To deal with , Therefore, the following capabilities can be realized :

function foo() { console.log(this.name);  }
​
const fooWithName = throttle(200, foo);
​
const obj = {name: 'elvin'};
​
fooWithName.call(obj, 'elvin');
​
// => 'elvin'
 Copy code 

debounce Realization

because  debouncen Just postpone the execution time of the function , Do not have  throttle  The ability to perform at regular intervals , So it's easier to implement :

function debounce(delay, callback) {
  let timeoutID;
​
  function wrapper() {
    const self = this;
    const args = arguments;
​
    function exec() {
      callback.apply(self, args);
    }
​
    clearTimeout(timeoutID);
​
    timeoutID = setTimeout(exec, delay);
  }
​
  return wrapper;
}
 Copy code 

Compare the above code with  throttle  Compared with the implemented code , It can be found that it is the removal of  elapsed  Code after relevant logic , Most of the rest as like as two peas , therefore  debounce  Function can be used with  throttle  Function implementation (throttle-debounce  This is also done in the source code ),throttle  Functions can also use  debounce  Function implementation .

Use scenario example

throttle  and  debounce  It is applicable to scenarios where users frequently perform the same operation in a short time , for example :

  • The user drags the browser window to change the window size , Trigger  resize  event .
  • The user moves the mouse , Trigger  mousemove  Other events .
  • The user enters in the input box , Trigger  keydown | keypress | keyinput | keyup  Other events .
  • The user scrolls the screen , Trigger  scroll  event .
  • After the user clicks the button , because API The request took too long to see the response immediately , You may keep clicking on the button to trigger  click  event .

To be improved

iOS Implementation of version .

quote

  1. zhuanlan.zhihu.com/p/43410181
  2. www.runoob.com/w3cnote/js-…
  3. demo.nimius.net/debounce_th…

copyright notice
author[Little star_ ios],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827064030436S.html

Random recommended