-
Notifications
You must be signed in to change notification settings - Fork 1
/
set-timer.js
34 lines (30 loc) · 933 Bytes
/
set-timer.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
var setTimer = function (cb, options) {
options = options || Object.prototype;
options.timeout = options.timeout || 0;
options.interval = options.interval || 0;
options.limit = options.limit || 1;
options.onClear = options.onClear || Function.prototype;
options.cb = cb || Function.prototype;
var timer = {
calls: 0,
options: options,
timeout: null,
interval: null,
clear: function () {
if (this.timeout) clearTimeout(this.timeout);
if (this.interval) clearInterval(this.interval);
options.onClear.call(this);
}
};
timer.timeout = setTimeout(function () {
timer.interval = setInterval(function() {
timer.calls++;
options.cb.call(timer);
if (timer.calls >= options.limit) {
timer.clear();
}
}, options.interval);
}, options.timeout);
return timer;
};
module.exports = setTimer;