Skip to content

Commit a90ca59

Browse files
committed
add throttle utility in typescript
1 parent ccfe368 commit a90ca59

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

TypeScript/throttle.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)