We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent ccfe368 commit a90ca59Copy full SHA for a90ca59
1 file changed
TypeScript/throttle.ts
@@ -0,0 +1,26 @@
1
+// basic throttle - limits how often a function can fire
2
+// useful for scroll handlers, resize events etc
3
+
4
+function throttle<T extends (...args: any[]) => void>(
5
+ fn: T,
6
+ limit: number
7
+): (...args: Parameters<T>) => void {
8
+ let lastCall = 0;
9
10
+ return function(...args: Parameters<T>) {
11
+ const now = Date.now();
12
+ if (now - lastCall >= limit) {
13
+ lastCall = now;
14
+ fn(...args);
15
+ }
16
+ };
17
+}
18
19
+// example - only fires once per 200ms max
20
+const onScroll = throttle(() => {
21
+ console.log('scroll event');
22
+}, 200);
23
24
+window.addEventListener('scroll', onScroll);
25
26
+export { throttle };
0 commit comments