We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent b44d5e7 commit 13f8243Copy full SHA for 13f8243
snippets/javascript/function-utilities/throttle-function.md
@@ -0,0 +1,25 @@
1
+---
2
+title: Throttle Function
3
+description: Ensures a function is only called at most once in a specified time interval. Useful for optimizing events like scrolling or resizing.
4
+author: WizardOfDigits
5
+tags: throttle,performance,optimization
6
7
+
8
+```js
9
+const throttle = (func, limit) => {
10
+ let inThrottle;
11
+ return (...args) => {
12
+ if (!inThrottle) {
13
+ func(...args);
14
+ inThrottle = true;
15
+ setTimeout(() => (inThrottle = false), limit);
16
+ }
17
+ };
18
+};
19
20
+// Usage:
21
+const logScroll = throttle(() => console.log("Scroll event triggered"), 1000);
22
23
+// Attach to scroll event
24
+window.addEventListener("scroll", logScroll);
25
+```
0 commit comments