diff --git a/snippets/javascript/function-utilities/throttle-function.md b/snippets/javascript/function-utilities/throttle-function.md new file mode 100644 index 00000000..d3ab8a78 --- /dev/null +++ b/snippets/javascript/function-utilities/throttle-function.md @@ -0,0 +1,26 @@ +--- +title: Throttle Function +description: Ensures a function is only called at most once in a specified time interval. Useful for optimizing events like scrolling or resizing. +author: WizardOfDigits +tags: throttle,performance,optimization +--- + +```js +const throttle = (func, limit) => { + let inThrottle; + return (...args) => { + if (!inThrottle) { + func(...args); + inThrottle = true; + setTimeout(() => (inThrottle = false), limit); + } + }; +}; + +// Usage: +// Ensures the function can only be called once every 1000 milliseconds +const logScroll = throttle(() => console.log("Scroll event triggered"), 1000); + +// Attach to scroll event +window.addEventListener("scroll", logScroll); +``` pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy