How to Throttle Function in JavaScript: Simple Guide
To throttle a function in JavaScript, use a wrapper that limits how often the function can run by enforcing a minimum delay between calls. This is done by tracking the last time the function ran and ignoring calls that happen too soon, typically using
setTimeout or timestamps.Syntax
The basic syntax for a throttle function involves creating a wrapper that takes a function and a delay time in milliseconds. It returns a new function that only allows the original function to run once per delay period.
func: The function you want to throttle.delay: The minimum time in milliseconds between calls.
javascript
function throttle(func, delay) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= delay) { lastCall = now; func.apply(this, args); } }; }
Example
This example shows a throttled function that logs the current time at most once every 2 seconds, even if called more often.
javascript
function throttle(func, delay) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= delay) { lastCall = now; func.apply(this, args); } }; } const logTime = () => console.log('Time:', new Date().toLocaleTimeString()); const throttledLogTime = throttle(logTime, 2000); // Simulate rapid calls every 500ms let count = 0; const intervalId = setInterval(() => { throttledLogTime(); count++; if (count === 6) clearInterval(intervalId); }, 500);
Output
Time: 10:00:00 AM
Time: 10:00:02 AM
Time: 10:00:04 AM
Common Pitfalls
Common mistakes include:
- Not preserving the
thiscontext inside the throttled function. - Using
setTimeoutincorrectly, causing delayed or missed calls. - Confusing throttling with debouncing, which delays execution until after events stop.
Here is a wrong and right way to preserve this:
javascript
// Wrong: loses 'this' context function throttleWrong(func, delay) { let lastCall = 0; return function() { const now = Date.now(); if (now - lastCall >= delay) { lastCall = now; func(); // 'this' is lost here } }; } // Right: preserves 'this' and arguments function throttleRight(func, delay) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= delay) { lastCall = now; func.apply(this, args); } }; }
Quick Reference
Remember these tips when throttling functions:
- Throttle limits how often a function runs over time.
- Use
Date.now()or timestamps to track calls. - Preserve
thisand arguments withapplyorcall. - Throttle is useful for scroll, resize, or input events.
- Debounce is different: it waits until events stop.
Key Takeaways
Throttle limits how often a function can run by enforcing a delay between calls.
Always preserve the function's context and arguments using
apply or call.Use throttling to improve performance on frequent events like scrolling or resizing.
Throttle differs from debounce; throttle runs at regular intervals, debounce waits for inactivity.
Test throttled functions to ensure they behave as expected under rapid calls.