From 13f8243cd0f9a5202d11715b267e43b270dce468 Mon Sep 17 00:00:00 2001 From: WizardOfDigits Date: Mon, 10 Feb 2025 15:56:02 +0545 Subject: [PATCH 1/2] feat(feature): add throttle function to limt function calls within a specified time frame --- .../function-utilities/throttle-function.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 snippets/javascript/function-utilities/throttle-function.md diff --git a/snippets/javascript/function-utilities/throttle-function.md b/snippets/javascript/function-utilities/throttle-function.md new file mode 100644 index 00000000..53f8ce57 --- /dev/null +++ b/snippets/javascript/function-utilities/throttle-function.md @@ -0,0 +1,25 @@ +--- +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: +const logScroll = throttle(() => console.log("Scroll event triggered"), 1000); + +// Attach to scroll event +window.addEventListener("scroll", logScroll); +``` From 7151add40e65de8bc7197d8cbc57900d46934b24 Mon Sep 17 00:00:00 2001 From: WizardOfDigits Date: Mon, 17 Feb 2025 00:32:52 +0545 Subject: [PATCH 2/2] chore:Add comment to explain throttling behavior in scroll event handler --- snippets/javascript/function-utilities/throttle-function.md | 1 + 1 file changed, 1 insertion(+) diff --git a/snippets/javascript/function-utilities/throttle-function.md b/snippets/javascript/function-utilities/throttle-function.md index 53f8ce57..d3ab8a78 100644 --- a/snippets/javascript/function-utilities/throttle-function.md +++ b/snippets/javascript/function-utilities/throttle-function.md @@ -18,6 +18,7 @@ const throttle = (func, 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