Skip to content

Anti-shake throttling in JavaScript

Anti-shake and throttling are both ways to solve performance problems caused by high-frequency trigger events.

Anti-shake means that after the event is triggered, wait for a certain period of time before executing the callback function. If the event is triggered again within the waiting time, wait for a certain period of time again. A common application scenario is to trigger a search after typing in an input box.

The following is a simple anti-shake function implementation:

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

Throttling means that the callback function is executed only once within a certain period of time. A common application scenario is to trigger a callback function when the page is scrolled.

Here is a simple throttling function implementation:

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

Source

See also  Compare two dates in JavaScript using moment.js

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.