Skip to content

Commit 5982063

Browse files
committed
Add throttle implementation
1 parent 3a4d9cb commit 5982063

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

JavaScript/c-throttle.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'use strict';
2+
3+
// Function throttling, executed once per interval
4+
5+
const throttle = (timeout, fn, ...args) => {
6+
let timer;
7+
let wait = false;
8+
let wrapped = null;
9+
10+
const throttled = (...par) => {
11+
timer = undefined;
12+
if (wait) wrapped(...par);
13+
};
14+
15+
wrapped = (...par) => {
16+
if (!timer) {
17+
timer = setTimeout(throttled, timeout, ...par);
18+
wait = false;
19+
return fn(...args.concat(par));
20+
} else {
21+
wait = true;
22+
}
23+
};
24+
25+
return wrapped;
26+
};
27+
28+
// Usage
29+
30+
const fn = (...args) => {
31+
console.log('Function called, args: ' + args);
32+
};
33+
34+
const ft = throttle(200, fn, 'value1');
35+
36+
const timer = setInterval(() => {
37+
fn('value2');
38+
ft('value3');
39+
}, 50);
40+
41+
setTimeout(() => {
42+
clearInterval(timer);
43+
}, 2000);

0 commit comments

Comments
 (0)