1. JavaScript What Is Debounce And Throttle

Huabin ZhangHuabin Zhang
2 min read

Debounce and Throttle are both methods used to optimize the triggering of high-frequency events.

They are mainly to reduce unnecessary function execution and improve performance.

1.1 Debounce

“ If your requirement is, wait until the user stops performing an action. “

Debounce prevents one event be mistaken for multiple happing.

// debonunce function
function debounce(callback, delaytime) {
  let timerout;
  return function (...args) {
    if (timerout) {
      // important!!!
      clearTimeout(timerout);
    }
    // define timer
    timerout = setTimeout(() => {
      callback.apply(this, args);
    }, delaytime);
  };
}
// target event is encapsulated in debounce function
const btnSubmitClick = debounce(() => {
  const inputValue = inputField.value;
  console.log("success submit value: ", inputValue);
}, 2000);

// encapsulated target event passes in the trigger event
if (btnSubmit) {
  btnSubmit.addEventListener("click", btnSubmitClick);
}

The key step of debounce is the timer reset operation.

Application Scenarios

  • Login, Test messaging and other buttons prevent users from clicking so fast that they send multiple requests

  • Search field input avoid requesting the server API for each input

  • Resizing the browser window, the resize event is too frequent

1.2 Throttle

Throttling is to control“ the flow of water” and the frequency of events, such as once in 1s or event once in 1 minute.

It is similar to the Rate Limit controlled by the server or gateway.

// throttle function
function throttle(callback, waittime) {
  let lastTime = 0;
  return function (...args) {
    const nowTime = new Date().getTime();
    // calculate the time interval whether satisfy the waittime
    if (nowTime - lastTime >= waittime) {
      // update the lasttime and call the target function in order to limit the frequency
      lastTime = nowTime;
      callback.apply(this, args);
    }
  };
}

// target function
const getServerStatus = throttle(() => {
  console.log("get server status: ", new Date().toLocaleTimeString());
}, 1000);

// Simulate the high frequency event
setInterval(() => {
  getServerStatus();
}, 100);

The key is to control the call frequency through the time interval.

Application Scenarios

  • The browser plays events and calculates progress information every second

  • Frequent API requests (Data polling, keep loading nearby points as you drag the map)

  • Mouse move (frequency limit for games and drawing applications)

0
Subscribe to my newsletter

Read articles from Huabin Zhang directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Huabin Zhang
Huabin Zhang