Home  >  Article  >  Web Front-end  >  Introduction to application scenarios of javascript function throttling and anti-shake

Introduction to application scenarios of javascript function throttling and anti-shake

不言
不言forward
2018-10-19 15:06:332639browse

This article brings you an introduction to the usage of PHP variable scope (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

throttle Throttle

The event is triggered and executed only once.

Application scenario

When the mousemove event is triggered, such as mouse movement.

Situations that trigger the keyup event, such as search.

When the scroll event is triggered, for example, loading data is triggered when the mouse stops scrolling down.

coding

Method 1 Anti-shake

// function resizehandler(fn, delay){
//   clearTimeout(fn.timer);
//   fn.timer = setTimeout(() => {
//      fn();
//   }, delay);
// }
// window.onresize = () => resizehandler(fn, 1000);

Method 2 Closure Anti-shake

function resizehandler(fn, delay){
    let timer = null;
    return function() {
      const context = this;
      const args=arguments;
      clearTimeout(timer);
      timer = setTimeout(() => {
         fn.apply(context,args);
      }, delay);
    }
 }
 window.onresize = resizehandler(fn, 1000);

debounce Anti-shake

Execute once within a certain event after the event is triggered.

Application Scenario

The resize event triggered by window changes is only executed once.

To verify the phone number input, just stop inputting and perform it once.

coding

function resizehandler(fn, delay, duration) {
        let timer = null;
        let beginTime = +new Date();
        return function() {
          const context = this;
          const args = arguments;
          const currentTime = +new Date();
          timer && clearTimeout(timer);
          if ((currentTime - beginTime) >= duration) {
            fn.call(context, args);
            beginTime = currentTime;
           } else {
             timer = setTimeout(() => {
               fn.call(context, args)
             }, delay);
           }
        }
      }

        window.onresize = resizehandler(fn, 1000, 1000);

The above is the detailed content of Introduction to application scenarios of javascript function throttling and anti-shake. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete