Throttle Function in JavaScript
Level 5398 keystrokes
Throttle limits function calls to at most once per specified time period.
JavaScript code
// Throttle factory function1function throttle(fn, limit) { // Track if we're in throttle period2 let inThrottle = false; // Return throttled function3 return (...args) => { // Only execute if not in throttle period4 if (!inThrottle) { // Call the original function5 fn(...args); // Enter throttle period6 inThrottle = true; // Exit throttle period after limit ms7 setTimeout(() => {8 inThrottle = false;9 }, limit);10 }11 };12}13 // Counter for demo14let count = 0;// Create throttled function with 100ms limit15const log = throttle(() => {16 count++;17 console.log(`Called ${count}`);18}, 100);19 // Rapid calls - only first executes20log(); log(); log();// After 150ms - first call executes (throttle expired)21setTimeout(() => { log(); log(); }, 150);// Print total count22setTimeout(() => console.log(`Total: ${count}`), 300);Output
Called 1 Called 2 Total: 2
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