Typorithm · medium

debounce

debounceinterview-questionsclosuretimers
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn debounce

0%

Utility Functions

debounce collapses a burst of calls into one, firing fn only after activity stops for delay milliseconds. Each call clears the pending timer and starts a new one.

debounce returns a wrapper that delays invoking fn until callers stop firing it. It is ideal for search-as-you-type inputs and window resize handlers.

On every call it runs clearTimeout to cancel any pending invocation, then schedules a new one with setTimeout — so only the final call in a burst actually runs fn.

The timer id is held in a closure variable, letting consecutive calls of the returned function share and reset the same pending timer.

01

Fires fn once after a quiet period.

02

Each call resets the pending timer.

03

Great for search input and resize.

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Wrapper signature

debounce takes the function to defer and a delay, returning a new wrapped function.

function debounce(fn, delay) {

2. Persisted timer

The timer id lives in the closure so it survives across calls of the returned function.

let timer;

3. Cancel pending call

Each call cancels the previous pending timer, restarting the quiet period.

clearTimeout(timer);

4. Schedule the call

A fresh timer fires fn only after delay passes with no new calls.

timer = setTimeout(() => fn(...args), delay);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

debounce: Lesson & Practice · Typorithm | ApplyDjinn