I'm using Angular 5.
I want to know how can I start timing when a 'play' button is pressed, in order to know how much time has passed since I clicked.
I'd also like to know if it's possible to stop the timer and then be able to continue with the same time before.
I've finally solved my question with Pardeep Jain answer. Athough it wasn't exactly what I was looking for. I didn't want a countdown, I wanted to count the duration. Here is the code I've used at the end:
time: number = 0;
interval;
startTimer() {
this.play = true;
this.interval = setInterval(() => {
this.time++;
},1000)
}
pauseTimer() {
this.play = false;
clearInterval(this.interval);
}
This may be overkill for what you're looking for, but there is an npm package called
marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it vianpm
and then import the dependency anywhere you'd like to use it. Here is a link to thenpm
package: https://www.npmjs.com/package/markyAn example of use after installing via npm would be as follows:
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.You can simply use
setInterval
to create such timer in Angular, Use this Code for timer -Working Example
Another way using Observable timer like below -
Working Example
For more information read here