Limit function execution to once per specified time interval
Quick Answer
A throttle function ensures a callback is called at most once within a given time window. Unlike debounce, it fires on the leading edge and continues to fire at regular intervals as long as the trigger keeps occurring.
1function throttle(func, limit) {
2 let inThrottle;
3 return function(...args) {
4 if (!inThrottle) {
5 func.apply(this, args);
6 inThrottle = true;
7 setTimeout(() => inThrottle = false, limit);
8 }
9 };
10}A throttle function ensures that a function is called at most once in a specified time period. Unlike debounce which delays execution, throttle guarantees regular execution intervals. This is essential for performance optimization when dealing with high-frequency events like scrolling, mouse movements, or repeated button clicks.
Use throttle when you need guaranteed periodic execution, such as scroll progress bars or live previews. Use debounce when you want to wait for activity to stop, such as search-as-you-type.
50–100 ms works well for most scroll-driven UI updates. Lower values feel more real-time but use more CPU.
Yes. Any call that arrives while the throttle window is active is silently ignored unless you add trailing-call support.
This free javascript code snippet for throttle function is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement throttle function quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.