HomePremium · ₹1199
← All questions

Implement debounce (rate-limit API calls)

Medium
Asked at:MicrosoftGoogleAtlassian
Was this asked in an interview?

Build a debounce utility to stop a search-as-you-type box from hammering your API on every keystroke.

Problem

You are building a search-as-you-type box. Every keystroke currently fires an API request, so typing "react" sends five requests in under a second — wasting bandwidth, racing responses, and hammering your backend. You want to fire one request, only after the user pauses typing.

Implement debounce(fn, delay) that returns a debounced wrapper around fn.

  • Each call to the wrapper resets an internal timer.
  • fn runs once, with the most recent arguments, only after delay milliseconds have passed with no new calls.
  • The wrapper must preserve the caller's this.

The same tool powers autosave (save 500ms after the user stops editing), resize/scroll handlers, and any "wait for the dust to settle" behaviour.

Input

let requests = 0;
const search = debounce((query) => {
  requests++;
  fetch(`/api/search?q=${query}`);
}, 100);

search("r");
search("re");
search("rea");
search("react");
// user stops typing; wait > 100ms

Expected output

  • requests === 1 (a single call, not four)
  • That call uses the latest query, "react"

Implement from scratch:

function debounce(fn, delay) {
  // Your code here
}
Implement debounce (rate-limit API calls) — JavaScript Interview Question | Mentoxis