Debounce Function in JavaScript

Level 5424 keystrokes

This implements debounce to delay function execution until calls stop.

JavaScript code

// Debounce: delays execution until no calls for 'delay' ms
// Useful for search inputs, resize handlers, etc.
1function debounce(func, delay) {
// Store the timeout ID to cancel pending calls
2 let timeoutId;
3
// Return a wrapper function
4 return function(...args) {
// Cancel any pending execution
5 clearTimeout(timeoutId);
// Schedule new execution after delay
// Uses apply to preserve 'this' context and arguments
6 timeoutId = setTimeout(() => {
7 func.apply(this, args);
8 }, delay);
9 };
10}
11
// Original function that would run on every input
12function search(query) {
13 console.log(`Searching for: ${query}`);
14}
15
// Create debounced version with 300ms delay
16const debouncedSearch = debounce(search, 300);
17
// Rapid calls - only the last one executes
18debouncedSearch("hello");
19debouncedSearch("hello w");
20debouncedSearch("hello world");
21
// Wait to see the final result
22setTimeout(() => {
23 console.log("Done");
24}, 500);

Output

Searching for: hello world
Done
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 15
  • )× 15
  • ;× 12
  • "× 8
  • .× 6
  • {× 6
  • }× 6
  • ,× 5
  • =× 4
  • `× 2

More JavaScript examples at level 5

← JavaScript typing practice