Debounce is divided into non-immediate and immediate versions

The so-called shaking prevention 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.

Non-immediate version:

The non-immediate version means that the function is not executed immediately after the event is fired, but n seconds later. If the event is fired within n seconds, the function execution time is recalculated.

function debounce(func, wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        
        timeout = setTimeout(() = >{ func.apply(context, args) }, wait); }}Copy the code
Immediate release

The immediate execution version means that the function is executed immediately after the event is fired, and then the effect of the function cannot be continued until the event is fired for n seconds.

  function debounceFun(func,wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;
        if (timeout) clearTimeout(timeout);
        letcallNow = ! timeout; timeout =setTimeout(() = > {
            timeout = null;
        }, wait)
        if (callNow) func.apply(context, args)
    }
}
Copy the code

The throttle

The idea of throttling is to allow a function to execute sparingly, rather than arbitrarily once triggered. What does abstinence mean? Just do it once in a period of time.

  function throttleFun(func, wait){
    let run = true;
    return function(){
      if(! run)return ;
      run = false;
      setTimeout(() = >{
        func.apply(this.arguments);
        run = true;
      },wait)
    }
  }
Copy the code

Refer to the article: www.jianshu.com/p/c8b86b09d…