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 called1function throttle(fn, delay) { // Track when the function was last called2 let lastCall = 0; // Return a wrapper function3 return function(...args) { // Get current timestamp4 const now = Date.now(); // Only execute if enough time has passed since last call5 if (now - lastCall >= delay) { // Update last call time6 lastCall = now; // Execute the original function with proper this and args7 fn.apply(this, args);8 }9 };10}11 // Counter for demonstration12let count = 0;// Create throttled function with 100ms delay13const 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. 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