AniUI Academy
medium+250 XPPractice

Debounce on the leading edge

Ordinary debounce is trailing: it waits for quiet, then acts. That is right for a search box and wrong for a button, where the user needs feedback now and protection from double-clicks after. Leading-edge debounce inverts it: act immediately, then swallow everything until things go quiet.

Implement leadingDebounce(fn, wait). It returns a wrapper. If no cooldown is currently pending, the wrapper invokes fn immediately, synchronously, with the same arguments and the same this, and returns fn's return value. Every call — whether or not it invoked fn — then starts a fresh cooldown of wait milliseconds, restarting any cooldown already running. While a cooldown is pending, calls do not invoke fn and return undefined. Only once a full wait has passed with no calls at all does the next call invoke fn again. There is no trailing call: the calls swallowed during a cooldown are never run later.

What it has to do

  • Invoke fn synchronously on the first call and return its result.
  • Suppress the rest of a burst and return undefined for suppressed calls.
  • Never make a trailing call once the burst ends.
  • Restart the cooldown on every call, so a steady stream of calls closer together than wait only ever fires once.
  • Invoke fn again on the first call after a full wait of silence.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.