Skip to content

Commit ad64947

Browse files
authored
Merge pull request #259 from WizardOfDigits/main
feat(feature): add throttle function to limt function calls within a …
2 parents 2b10de9 + 868b59d commit ad64947

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
```

0 commit comments

Comments
 (0)