Handwriting anti-shake, throttling

concept:

  • Anti-shake: Execute the callback after n seconds after the event is triggered. If the event is triggered again within n seconds, the timing will be restarted
  • Throttling: Within the specified time, there can only be one callback that triggers the event, and it will not take effect if it is triggered repeatedly within the unit time

Application scenario:

  • Anti-shake: input box input (input)...
  • Throttling: Browser window change (resize), page scrolling (scroll), dragging (drag)...

Anti-shake:

function debounce(fn, delay) {
  let timer = null;
  return function () {
    if(timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, delay)
  }
}

* * throttling:

function throttle(fn, delay) {
  let timer = null;
  return function () {
    if(timer) return;
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, delay)
  }
}

transfer:

const btn = document.querySelector('button')
btn.addEventListener('click', debounce(function () {
  console.log('发财小手点个关注')
}, 1000, true))

Guess you like

Origin blog.csdn.net/qq_37215621/article/details/131482929