DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 24

The task is to implement a debounce method. A debounce is used to control how often a function is invoked.

The boilerplate code is

function debounce(func, wait) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

First, a variable to keep track of the timer(period of delay) is created

let timeoutId
Enter fullscreen mode Exit fullscreen mode

A function that will be returned when the timer is set is then created. The function checks if there's an existing timer, and clears it. After the timer is set, the original function is called after the delay period.

return function (...args) {
    const context = this;

    clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };

Enter fullscreen mode Exit fullscreen mode

The final code is:

function debounce(func, wait) {
  // your code here
  let timeoutId;

  return function(...args) {
    const context = this;

    clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      func.apply(context, args)
    }, wait)
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)