Limit function execution to once per specified time interval
1function throttle(func, limit) {
2 let inThrottle;
3
4 return function(...args) {
5 if (!inThrottle) {
6 func.apply(this, args);
7 inThrottle = true;
8 setTimeout(() => inThrottle = false, limit);
9 }
10 };
11}
12
13// Usage example
14const handleScroll = throttle(() => {
15 console.log('Scroll position:', window.scrollY);
16}, 1000);
17
18window.addEventListener('scroll', handleScroll);Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.