Back to Snippets
Throttle Function
javascript
JavaScript
Limit function execution to once per specified time period. Great for scroll events.
Code
1function throttle(func, limit) {
2let inThrottle;
3return function(...args) {
4if (!inThrottle) {
5func.apply(this, args);
6inThrottle = true;
7setTimeout(() => inThrottle = false, limit);
8}
9};
10}
11
12// Usage
13const throttledScroll = throttle(() => {
14console.log("Scroll event fired");
15}, 100);
16
17window.addEventListener("scroll", throttledScroll);Details
Language
javascript
Category
JavaScript