Throttle Function in JavaScript: What It Is and How It Works
throttle function in JavaScript limits how often a function can run over time. It ensures the function runs at most once every specified interval, helping control events that fire rapidly like scrolling or resizing.How It Works
Imagine you have a friend who talks very fast and you want to hear only one sentence every few seconds. The throttle function acts like a filter that only lets one sentence through in a set time, ignoring the rest until the time passes.
In JavaScript, when an event like scrolling or resizing happens many times quickly, the throttle function makes sure the related code runs only once every set number of milliseconds. This prevents the code from running too often and slowing down the page.
Example
This example shows a throttle function that limits how often a message logs when the window is resized.
function throttle(func, limit) { let lastFunc; let lastRan; return function() { const context = this; const args = arguments; if (!lastRan) { func.apply(context, args); lastRan = Date.now(); } else { clearTimeout(lastFunc); lastFunc = setTimeout(function() { if ((Date.now() - lastRan) >= limit) { func.apply(context, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; } const logResize = () => console.log('Window resized at', new Date().toLocaleTimeString()); window.addEventListener('resize', throttle(logResize, 2000));
When to Use
Use throttle when you want to limit how often a function runs during frequent events like scrolling, resizing, mouse movements, or key presses. This helps improve performance and user experience by preventing too many function calls.
For example, if you want to update a progress bar while scrolling but don't want it to update hundreds of times per second, throttle can make it update only once every 100 milliseconds.
Key Points
- Throttle limits function calls to once per time interval.
- It helps control performance-heavy events.
- Unlike
debounce, throttle runs the function regularly, not just after events stop. - Useful for scroll, resize, and input events.