js realizes throttling and anti-shake

Code

Anti-shake:

It means to trigger events continuously but only execute the last time within a set period of time, for example: set 1000 milliseconds to execute, when you trigger an event, it will execute after 1000 milliseconds, but when there are 500 milliseconds left you If the event is triggered again, it will restart after 1000 milliseconds.

Memory Core : Start Over

Application scenario : search box search input text editor save in real time 

  let timerId = null
  document.querySelector('.int').onkeyup = function(){
    // 防抖
    if(timerId!== null){
      clearInterval(timerId)
    }
    timerId = setTimeout(() => {
      console.log("我是防抖");
    }, 1000);
  }

Throttling:

It means that the event is triggered continuously but the function is only executed once in a set period of time. For example: if you set the execution time to 1000 milliseconds, then you trigger multiple times at 1000 milliseconds, and only execute once after 1000 milliseconds

Memory method : don't interrupt me

Application scenarios: high-frequency events such as quick clicks, mouse sliding, resize events, and scroll events. Pull down to load video playback, etc.

  let timerId = null
  document.querySelector('.int').onmouseover = function(){
    // 节流
    if(timerId!== null){
     return
    }
    timerId = setTimeout(() => {
      console.log("我是节流");
      timerId = null
    }, 1000);
  }

In fact, I usually use the lodash library for development, and use the debounce (anti-shake) and throttle (throttle) in it to do it.

おすすめ

転載: blog.csdn.net/cx1361855155/article/details/128142162