Back to library
📜JavaScriptjavascriptintermediate

Throttle Function

Limit function execution to once per specified time interval

performanceoptimizationtiming

Code

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);

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.