-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground-timer.js
100 lines (87 loc) · 2.68 KB
/
background-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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var BackgroundTimer, timer;
BackgroundTimer = (function() {
function BackgroundTimer(interval, callback) {
this.interval = interval;
this.callback = callback;
}
BackgroundTimer.prototype.start = function() {
console.log("starting");
if (this.tickingEnabled) {
this.startTicking();
}
this.timerID = setTimeout((function(_this) {
return function() {
_this.callback();
return _this.cancel();
};
})(this), this.interval);
document.addEventListener('resume', (function(_this) {
return function() {
console.log("resume");
return _this.wakeup();
};
})(this), false);
this.expirationDate = moment(moment() + this.interval);
return this.running = true;
};
BackgroundTimer.prototype.getRemaining = function() {
return this.expirationDate - moment();
};
BackgroundTimer.prototype.wakeup = function() {
var remaining;
if (this.running) {
remaining = this.getRemaining();
this.cancel();
if (remaining > 0) {
this.constructor(remaining, this.callback);
return this.start();
} else {
this.callback();
return this.cancel;
}
}
};
BackgroundTimer.prototype.enableTicking = function(tickInterval, tickCallback) {
this.tickInterval = tickInterval;
this.tickCallback = tickCallback;
return this.tickingEnabled = true;
};
BackgroundTimer.prototype.pauseTicking = function() {
if (this.tickerID) {
clearInterval(this.tickerID);
return this.tickerID = null;
}
};
BackgroundTimer.prototype.resumeTicking = function() {
return this.startTicking();
};
BackgroundTimer.prototype.roundTime = function(time) {
return Math.floor((time + 100) / 1000) * 1000;
};
BackgroundTimer.prototype.startTicking = function() {
if (this.tickingEnabled) {
return this.tickerID = setInterval((function(_this) {
return function() {
return _this.tickCallback(_this.roundTime(_this.getRemaining()));
};
})(this), this.tickInterval);
}
};
BackgroundTimer.prototype.disableTicking = function() {
if (this.tickerID) {
this.tickingEnabled = false;
clearInterval(this.tickerID);
return this.tickerID = null;
}
};
BackgroundTimer.prototype.cancel = function() {
console.log("cancel");
if (this.running) {
this.running = false;
this.pauseTicking();
clearTimeout(this.timerID);
return this.timerID = null;
}
};
return BackgroundTimer;
})();