-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimer.js
More file actions
69 lines (61 loc) · 1.12 KB
/
Timer.js
File metadata and controls
69 lines (61 loc) · 1.12 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
69
/**
* This object manages the time of the active question.
*/
class Timer {
/**
* Starts the timer.
*
* @param {number} seconds - the number of seconds to count
*/
count(seconds) {
this.reset();
this.seconds = seconds;
this.interval = setInterval(this.onCountHandler, 1000);
}
/**
* Resets the timer.
*/
reset() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
/**
* Sets a listener to the count event.
*
* @param {Function} callback - the listener
*/
onCount(callback) {
this.onCountHandler = () => {
if (this.isOutOfTime()) {
this.reset();
this.fireOutOfTime();
}
if (this.interval) {
callback(--this.seconds);
}
};
}
/**
* Returns true if there are no more seconds to count, false otherwise.
*/
isOutOfTime() {
return !this.seconds;
}
/**
* Sets a listener to the out of time event.
*
* @param {Function} callback - the listener
*/
onOutOfTime(callback) {
this.onOutOfTimeHandler = callback;
}
/**
* Fires the out of time event.
*/
fireOutOfTime() {
this.onOutOfTimeHandler();
}
}
module.exports = Timer;