-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimers.js
59 lines (49 loc) · 1.3 KB
/
timers.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
let webTimers = {
timer: class Timer {
constructor(selector) {
this.el = $(selector);
}
init(format) {
this.format = format;
console.log(`[WEBTIMERS]: Timer initialized with format ${this.format}`);
}
async start(duration, unit, callback) {
this.duration = duration;
this.unit = unit;
this.timerStart = moment().format('X');
this.timerEnd = await getEnd(duration, unit);
this.el.text(moment(moment.duration(this.timerEnd, 'X').asSeconds(), 's').format(this.format));
let timesRun = 0;
this.timerInterval = setInterval(() => {
executeTimer(this);
}, 250);
function executeTimer(mainThis) {
timesRun++;
let val = timestamp(mainThis.timerEnd);
let formatted = moment(val.asSeconds(), 's');
formatted = moment(formatted, 's').format(mainThis.format);
if (timesRun >= 2) {
mainThis.el.text(formatted);
}
if (val.asSeconds() == 0) {
mainThis.stop();
callback();
}
}
function timestamp(timerEnd) {
let now = moment().format('X');
let diff = timerEnd - now;
diff = moment.duration(diff, 's');
return diff;
}
function getEnd(duration, unit) {
let res = moment().add(duration, unit).format('X');
console.log(res);
return res;
}
}
stop() {
clearInterval(this.timerInterval);
}
}
};