forked from yannbf/ionic3-components
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.ts
More file actions
87 lines (72 loc) · 2.3 KB
/
timer.ts
File metadata and controls
87 lines (72 loc) · 2.3 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { Component, Input } from '@angular/core';
export interface CountdownTimer {
seconds: number;
secondsRemaining: number;
runTimer: boolean;
hasStarted: boolean;
hasFinished: boolean;
displayTime: string;
}
@Component({
selector: 'timer',
templateUrl: 'timer.html'
})
export class Timer {
@Input() timeInSeconds: number;
timer: CountdownTimer;
constructor() { }
ngOnInit() {
this.initTimer();
}
hasFinished() {
return this.timer.hasFinished;
}
initTimer() {
if (!this.timeInSeconds) { this.timeInSeconds = 0; }
this.timer = <CountdownTimer>{
seconds: this.timeInSeconds,
runTimer: false,
hasStarted: false,
hasFinished: false,
secondsRemaining: this.timeInSeconds
};
this.timer.displayTime = this.getSecondsAsDigitalClock(this.timer.secondsRemaining);
}
startTimer() {
this.timer.hasStarted = true;
this.timer.runTimer = true;
this.timerTick();
}
pauseTimer() {
this.timer.runTimer = false;
}
resumeTimer() {
this.startTimer();
}
timerTick() {
setTimeout(() => {
if (!this.timer.runTimer) { return; }
this.timer.secondsRemaining--;
this.timer.displayTime = this.getSecondsAsDigitalClock(this.timer.secondsRemaining);
if (this.timer.secondsRemaining > 0) {
this.timerTick();
}
else {
this.timer.hasFinished = true;
}
}, 1000);
}
getSecondsAsDigitalClock(inputSeconds: number) {
var sec_num = parseInt(inputSeconds.toString(), 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
var hoursString = '';
var minutesString = '';
var secondsString = '';
hoursString = (hours < 10) ? "0" + hours : hours.toString();
minutesString = (minutes < 10) ? "0" + minutes : minutes.toString();
secondsString = (seconds < 10) ? "0" + seconds : seconds.toString();
return hoursString + ':' + minutesString + ':' + secondsString;
}
}