Skip to content

Commit 7843c40

Browse files
committed
Initial commit
1 parent 9d8dc11 commit 7843c40

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

src/throttle.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
var throttle = function(delay, callback) {
2+
3+
// last time callback was executed.
4+
var lastExec = 0;
5+
6+
// returned by setTimeout
7+
var timeout;
8+
9+
// Clear existing timeout
10+
function clearExistingTimeout() {
11+
if (timeout) {
12+
clearTimeout(timeout);
13+
}
14+
}
15+
16+
/*
17+
* Wrap the callback inside a throttled function
18+
*/
19+
function wrapper() {
20+
21+
var self = this;
22+
var elapsed = Date.now() - lastExec;
23+
var args = arguments;
24+
25+
// Execute callback function
26+
function exec() {
27+
lastExec = Date.now();
28+
callback.apply(self, args);
29+
}
30+
31+
clearExistingTimeout();
32+
33+
// Execute
34+
if (elapsed > delay) {
35+
exec();
36+
}
37+
// Schedule for a later execution
38+
else {
39+
timeout = setTimeout(exec, delay - elapsed);
40+
}
41+
}
42+
43+
// Return the wrapper function.
44+
return wrapper;
45+
}
46+
47+
module.exports = throttle;

test/throttle.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
var assert = require('assert');
2+
var throttle = require('../src/throttle');
3+
4+
function sleep(ms) {
5+
return new Promise(resolve => setTimeout(resolve, ms));
6+
}
7+
8+
describe('throttle', function() {
9+
10+
it('function shouldn\'t be throttled (30 function calls in 600ms)', async function() {
11+
this.timeout(5000);
12+
var functionCalls = 30;
13+
var sleepTime = 20; // 30*20 = 600 ms
14+
var expectedExecutions = 30; // Function called in every iteration
15+
var executions = 0;
16+
17+
var f = function() {
18+
executions++;
19+
};
20+
21+
for (var i=0; i<functionCalls; i++) {
22+
f();
23+
await sleep(sleepTime);
24+
}
25+
26+
assert.equal(expectedExecutions, executions);
27+
});
28+
29+
it('function should be throttled (4 function calls in 600ms', async function() {
30+
this.timeout(5000);
31+
var functionCalls = 30;
32+
var sleepTime = 20; // 30*20 = 600 ms
33+
var throttleDelay = 200;
34+
var expectedExecutions = 3 + 1; // Call functions for 600 ms with 200 ms throttle = 3 calls + one last call
35+
var executions = 0;
36+
37+
var f = throttle(throttleDelay, function() {
38+
executions++;
39+
});
40+
41+
for (var i=0; i<functionCalls; i++) {
42+
f();
43+
await sleep(sleepTime);
44+
}
45+
46+
assert.equal(expectedExecutions, executions);
47+
});
48+
49+
});

0 commit comments

Comments
 (0)