javascriptadvanced10 minutes

Fix Bug in Advanced Debounce Function Implementation

Identify and fix the bug in the provided advanced debounce function implementation that prevents it from correctly delaying callback execution and handling immediate invocations.

Challenge prompt

You are given a debounce function that is intended to delay the invocation of a callback until after a specified wait time has elapsed since the last time the debounced function was called. It also supports an 'immediate' flag to trigger the callback at the start instead of the end of the delay period. However, the existing implementation contains a logical bug causing unexpected multiple invocations or no invocation at all in certain edge cases. Your task is to find and fix the bug so the debounce function works as expected in all scenarios.

Guidance

  • Carefully analyze how the timer is being managed and reset inside the function.
  • Pay special attention to the behavior when the 'immediate' flag is set to true.
  • Check how the context and arguments are preserved for callback invocation.

Hints

  • The current implementation incorrectly handles the clearing of the timer which leads to missed or repeated calls.
  • Review where the timer is reset and when the callback is finally invoked.
  • Remember that when 'immediate' is true, the callback should trigger on the leading edge, not the trailing edge.

Starter code

function debounce(func, wait, immediate) {
  let timeout;
  return function() {
    const context = this,
          args = arguments;
    const later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

// Example usage:
// const debouncedLog = debounce(() => console.log('Called!'), 1000, true);
// debouncedLog();
// debouncedLog();
// Expected output: 'Called!' only once immediately on first call

Expected output

'Called!' printed only once on first call when immediate is true, and exactly once after delay when immediate is false.

Core concepts

debouncetimersclosuresfunction context (this)

Challenge a Friend

Send this duel to someone else and see if they can solve it.