-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpauseable-timeout.js
More file actions
68 lines (58 loc) · 1.73 KB
/
pauseable-timeout.js
File metadata and controls
68 lines (58 loc) · 1.73 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict';
var _ = require('lodash');
module.exports = customSetTimeout;
var STATE_INITIALIZED = 'initialized',
STATE_STARTED = 'started',
STATE_PAUSED = 'paused',
STATE_RESUMED = 'resumed',
STATE_FINISHED = 'finished',
STATE_ABORTED = 'aborted';
function customSetTimeout(callback, duration) {
return new Timeout(callback, duration, _.slice(arguments, 2));
}
function Timeout(callback, duration, callbackArguments) {
this.callbackArguments = callbackArguments;
this.state = STATE_INITIALIZED;
this.callback = callback;
this.remaining = duration;
this.start();
}
Timeout.prototype.start = function() {
if (this.state === STATE_INITIALIZED || this.state === STATE_PAUSED) {
this.state = this.state === STATE_INITIALIZED ? STATE_STARTED : STATE_RESUMED;
this.startedAt = new Date().getTime();
this.timeout = setTimeout(function (that) {
that.state = STATE_FINISHED;
that.callback.apply(null, that.callbackArguments);
}, this.remaining, this);
}
};
Timeout.prototype.pause = function () {
if (this.state === STATE_STARTED || this.state === STATE_RESUMED) {
this.state = STATE_PAUSED;
this.remaining = this.remaining - (new Date().getTime() - this.startedAt);
clearTimeout(this.timeout);
this.timeout = null;
return this.remaining;
}
return false;
};
Timeout.prototype.resume = function () {
if (this.state === STATE_PAUSED) {
this.start();
return true;
}
return false;
};
Timeout.prototype.abort = function () {
if (this.state === STATE_STARTED ||
this.state === STATE_RESUMED ||
this.state === STATE_PAUSED) {
this.state = STATE_ABORTED;
clearTimeout(this.timeout);
this.callback = this.callbackArguments = this.timeout = null;
return true;
}
return false;
};
Timeout.prototype.state = null;