Coding Challenge Practice - Question 117

Published: (February 9, 2026 at 09:25 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Problem Description

Implement an enhanced debounce function that supports options to invoke the wrapped function immediately (leading) or after a delay (trailing).

Solution Overview

  1. State variables

    • timer: holds the current timeout identifier.
    • lastArgs / lastThis: store the most recent arguments and context.
  2. When the debounced function is called

    • Save the arguments and this context.
    • Determine if the function should be called immediately (option.leading && !timer).
    • Clear any existing timer.
    • Set a new timer that, after wait milliseconds, will invoke the original function if option.trailing is enabled and there are pending arguments.
  3. Immediate execution

    • If shouldCallNow is true, invoke the original function right away and reset stored arguments.

Code

function debounce(func, wait, option = { leading: false, trailing: true }) {
  let timer = null;
  let lastArgs;
  let lastThis;

  return function (...args) {
    lastArgs = args;
    lastThis = this;

    const shouldCallNow = option.leading && !timer;

    if (timer) clearTimeout(timer);

    timer = setTimeout(() => {
      timer = null;

      if (option.trailing && lastArgs) {
        func.apply(lastThis, lastArgs);
        lastArgs = lastThis = null;
      }
    }, wait);

    if (shouldCallNow) {
      func.apply(lastThis, lastArgs);
      lastArgs = lastThis = null;
    }
  };
}
0 views
Back to Blog

Related posts

Read more »