Home > Web Front-end > JS Tutorial > body text

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

不言
Release: 2018-10-19 15:06:33
forward
2654 people have browsed it

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);
Copy after login

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template