Throttle Function in JavaScript

Level 5398 keystrokes

Throttle limits function calls to at most once per specified time period.

JavaScript code

// Throttle factory function
1function throttle(fn, limit) {
// Track if we're in throttle period
2 let inThrottle = false;
// Return throttled function
3 return (...args) => {
// Only execute if not in throttle period
4 if (!inThrottle) {
// Call the original function
5 fn(...args);
// Enter throttle period
6 inThrottle = true;
// Exit throttle period after limit ms
7 setTimeout(() => {
8 inThrottle = false;
9 }, limit);
10 }
11 };
12}
13
// Counter for demo
14let count = 0;
// Create throttled function with 100ms limit
15const log = throttle(() => {
16 count++;
17 console.log(`Called ${count}`);
18}, 100);
19
// Rapid calls - only first executes
20log(); log(); log();
// After 150ms - first call executes (throttle expired)
21setTimeout(() => { log(); log(); }, 150);
// Print total count
22setTimeout(() => console.log(`Total: ${count}`), 300);

Output

Called 1
Called 2
Total: 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.

  • (× 19
  • )× 19
  • ;× 17
  • =× 10
  • .× 8
  • {× 8
  • }× 8
  • ,× 5
  • >× 5
  • `× 4

More JavaScript examples at level 5

← JavaScript typing practice