-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.js
34 lines (30 loc) · 910 Bytes
/
throttle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Throttle function to limit the execution of a callback.
* @param {function} callback - The function to be throttled.
* @param {number} limit - The time limit in milliseconds.
* @returns {function} - The throttled function.
*/
export const throttle = (callback, limit) => {
let inThrottle = false;
return (...args) => {
if (!inThrottle) {
callback(...args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
};
// // Example usage:
// const throttledFunction = throttle(() => {
// console.log("Throttled function executed");
// }, 200);
//
// // Call the throttled function
// throttledFunction();
//
// setTimeout(() => throttledFunction(), 200);
// setTimeout(() => throttledFunction(), 500);
// setTimeout(() => throttledFunction(), 800);
// setTimeout(() => throttledFunction(), 1100);