Debounce Function in JavaScript

Level 4263 keystrokes

Debounce delays function execution until after a pause in calls.

JavaScript code

// Debounce factory function
1function debounce(fn, delay) {
// Store timeout ID in closure
2 let timeoutId;
// Return a debounced function
3 return (...args) => {
// Clear previous timeout on each call
4 clearTimeout(timeoutId);
// Set new timeout - fn only runs after delay with no calls
5 timeoutId = setTimeout(() => fn(...args), delay);
6 };
7}
// Create a debounced logger with 100ms delay
8const log = debounce(x => console.log(x), 100);
// Rapid calls - only last one (3) will execute
9log(1); log(2); log(3);
// Print "done" after debounced call completes
10setTimeout(() => console.log("done"), 200);

Output

3
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.

  • (× 14
  • )× 14
  • ;× 9
  • .× 8
  • =× 6
  • ,× 4
  • >× 4
  • "× 2
  • {× 2
  • }× 2

More JavaScript examples at level 4

← JavaScript typing practice