Throttle Function in JavaScript

Level 5309 keystrokes

Implements throttle to limit function execution to once per time interval.

JavaScript code

// throttle limits how often a function can be called
1function throttle(fn, delay) {
// Track when the function was last called
2 let lastCall = 0;
// Return a wrapper function
3 return function(...args) {
// Get current timestamp
4 const now = Date.now();
// Only execute if enough time has passed since last call
5 if (now - lastCall >= delay) {
// Update last call time
6 lastCall = now;
// Execute the original function with proper this and args
7 fn.apply(this, args);
8 }
9 };
10}
11
// Counter for demonstration
12let count = 0;
// Create throttled function with 100ms delay
13const log = throttle(() => console.log(++count), 100);
// Call 3 times immediately: only first executes (1)
14log(); log(); log();
// After 150ms, call twice: only first executes (2)
15setTimeout(() => { log(); log(); }, 150);

Output

1
2
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
  • ;× 13
  • =× 8
  • .× 6
  • ,× 4
  • {× 4
  • }× 4
  • >× 3
  • +× 2

More JavaScript examples at level 5

← JavaScript typing practice