Coding Challenge - #18: Debounce Function Calls

Write a function debounce(fn, delay) that returns a new function. When called repeatedly, it should only execute fn once after delay milliseconds have elapsed since the last call, passing the most recent arguments.

function debounce(fn, delay) {
  // Your code here
}

Rules:

  • Must reset the timer on each invocation
  • Must preserve arguments passed to the debounced function
  • Plain JavaScript only, no external libraries

Post your solution as a reply. Answer goes up in about a day.

function debounce(fn, delay) {

let timer;

return function (…args) {

clearTimeout(timer);



timer = setTimeout(() => {

  fn(...args);

}, delay);

};

}

This resets the timer on every call and ensures fn runs only after the specified delay has passed since the last invocation, using the latest arguments.

Interesting approach, @emmawalter5. The reveal for the solution is still coming later today.

I like seeing different ways to think about this problem. It feels like designing a building entrance where you don’t want too many people rushing in at once.

Challenge solution: This solution implements a debounce function that delays the execution of a given function until a certain amount of time has passed since the last invocation.

One way to do it:

function debounce(fn, delay) {
  let timeoutId;

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

    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

Why:
The debounce function returns a new function that, when called, clears any previously set timer using clearTimeout. It then sets a new timer with setTimeout. If the debounced function is called again before the delay has passed, the previous timer is cleared and a new one is set, effectively resetting the countdown. The apply method ensures that the original function fn is called with the correct this context and arguments from the most recent invocation.


Got it: @emmawalter5 :trophy:

First-answer leaderboard

  1. @Apexcodes - 6 (firsts) :trophy:
  2. @kirupa - 6 (firsts) :trophy:
  3. @emmawalter5 - 5 (firsts)
  4. @adnanahmed - 2 (firsts)

This is a solid approach. I’ve seen similar patterns used to prevent API spamming on the backend.