问题描述
我正在使用Angular 5.
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.
我终于用Pardeep Jain的答案解决了我的问题.尽管这不是我要找的东西.我不想倒数,我想计算持续时间.这是我最后使用的代码:
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);
}
推荐答案
您可以简单地使用setInterval
在Angular中创建此类计时器,将此代码用于计时器-
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
工作示例
使用Observable计时器的另一种方式,如下所示-
Working Example
Another way using Observable timer like below -
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
有关更多信息,在此处阅读
这篇关于如何在Angular 5中执行计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!