Exercise 1: Debounce (real-world)

Problem Statement

Create a function debounce(fn, delay) that calls fn only when no new call occurs within delay ms after last call. Use-case: search input.

Sample Output:

const debouncedSearch = debounce((query) => console.log(query), 300);
debouncedSearch("h"); debouncedSearch("he"); debouncedSearch("hel");
// After 300ms: only "hel" logged

Solution

const debounce = (fn, delay = 300) => {
  let t;
  return (...args) => {
    clearTimeout(t);
    t = setTimeout(() => fn(...args), delay);
  };
};

Explanation

Overall Goal:

  • Function ko delay ke baad hi execute karna.
  • Agar delay ke andar naya call aaye to pehle wala cancel karke naya timer start karna.
  • Use case: search input me typing ke time har keystroke pe API call nahi karna.

Line 1: Function header

  • const debounce = (fn, delay = 300) => {
  • fn → function jo execute hona hai.
  • delay = 300 → default delay 300ms (optional parameter).

Line 2: Timer storage

  • let t; → timer ID store karne ke liye variable.
  • let use kiya (not const) kyunki value change hogi.

Line 3: Return function

  • return (...args) => { → debounced function return karta hai:
  • ...args → spread operator: koi bhi number of arguments accept karega.
  • Ye function baad me call hoga, original fn ko delay ke saath execute karega.

Line 4: Clear previous timer

  • clearTimeout(t);
  • Agar pehle se koi timer running hai → usko cancel karo.
  • Isse guarantee hota hai ki sirf last call hi execute hogi.

Line 5: Set new timer

  • t = setTimeout(() => fn(...args), delay);
  • setTimeout → delay ke baad function execute karega.
  • () => fn(...args) → arrow function jo original function ko call karega.
  • t = ... → timer ID store karo, taaki baad me cancel kar sakein.

Example:

  • User types "h" → timer start (300ms).
  • User types "e" (100ms baad) → pehla timer cancel, naya timer start.
  • User types "l" (150ms baad) → pehla timer cancel, naya timer start.
  • User stops typing → 300ms baad function execute.

Real world:

  • Search input: typing ke time API call spam rokta hai.
  • Window resize: resize events ko throttle karta hai.
  • Button clicks: accidental double-clicks prevent karta hai.

Navigation

Previous

No previous exercise

Next

Exercise 2

View All Categories