File tree 1 file changed +26
-0
lines changed
snippets/javascript/function-utilities
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
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
+ // Ensures the function can only be called once every 1000 milliseconds
22
+ const logScroll = throttle (() => console .log (" Scroll event triggered" ), 1000 );
23
+
24
+ // Attach to scroll event
25
+ window .addEventListener (" scroll" , logScroll);
26
+ ```
You can’t perform that action at this time.
0 commit comments