Skip to content

Commit 13f8243

Browse files
feat(feature): add throttle function to limt function calls within a specified time frame
1 parent b44d5e7 commit 13f8243

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)