-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathchronometer.js
More file actions
52 lines (43 loc) · 1.37 KB
/
chronometer.js
File metadata and controls
52 lines (43 loc) · 1.37 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
class Chronometer {
constructor() {
this.currentTime = 0;
this.intervalId = null;
}
start(callback) {
this.intervalId = setInterval(() => {
this.currentTime++;
if (callback) {
callback(); // cada 10 ms se ejecuta el callback (la función que le pasemos)
}
}, 10); // Cada 10 ms incrementa el cronómetro (el update)
}
getMinutes() {
return Math.floor(this.currentTime / 6000); // 6000 ms = 1 minuto
}
getSeconds() {
return Math.floor((this.currentTime / 100) % 60); // 100 ms = 1 segundo
}
getMilliseconds() {
return this.currentTime % 100; // El resto son los ms
}
computeTwoDigitNumber(value) {
return value.toString().padStart(2, '0'); // Asegura que siempre tenga 2 dígitos (1 = 01, ...)
}
reset() {
this.currentTime = 0; // Reinicia el cronómetro a 0
}
stop() {
clearInterval(this.intervalId);
}
split() {
return `${this.computeTwoDigitNumber(this.getMinutes())}
:${this.computeTwoDigitNumber(this.getSeconds())}
:${this.computeTwoDigitNumber(this.getMilliseconds())}`;
// Es extraña la línea pero devolvemos un string con el formato MM:SS:MS, siempre en el formate de 2 dígitos
}
}
// The following is required to make unit tests work.
/* Environment setup. Do not modify the below code. */
if (typeof module !== 'undefined') {
module.exports = Chronometer;
}