-
Notifications
You must be signed in to change notification settings - Fork 0
/
_countdown.js
77 lines (65 loc) · 1.63 KB
/
_countdown.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
var Countdown = function(){}
Countdown.timer = function(end, onTick, onComplete) {
var timeLeft = end - new Date();
var timeAPI = {
DAYS: 1000 * 60 * 60 * 24,
HOURS: 1000 * 60 * 60,
MINUTES: 1000 * 60,
SECONDS: 1000
}
var tick = function() {
if(timeLeft > 0) {
var time = timeLeft
var days = Math.floor(time / (timeAPI.DAYS))
time %= timeAPI.DAYS
var hours = Math.floor(time / (timeAPI.HOURS))
time %= timeAPI.HOURS
var minutes = Math.floor(time / (timeAPI.MINUTES))
time %= timeAPI.MINUTES
var seconds = Math.floor(time / (timeAPI.SECONDS))
var countdown = {
days: days,
hours: hours,
minutes: minutes,
seconds: seconds
}
onTick(countdown)
timeLeft -= 1000
}else {
timeLeft -= 1000
clearInterval(interval),
onComplete()
}
}
var interval = setInterval(
(function(self){
return function(){
tick.call(self)
}
})(this), 1000
)
var getTimeRemaining = function() {
var time = timeLeft
var days = Math.floor(time / timeAPI.DAYS)
time %= timeAPI.DAYS
var hours = Math.floor(time / timeAPI.HOURS)
time %= timeAPI.HOURS
var minutes = Math.floor(time / timeAPI.MINUTES)
time %= timeAPI.MINUTES
var seconds = Math.floor(time / timeAPI.SECONDS)
return {
days: days,
hours: hours,
minutes: minutes,
seconds: seconds
}
}
tick.call(this)
return {
abort: function() {
clearInterval(interval)
},
getTimeRemaining: getTimeRemaining
}
}
module.exports = Countdown