如何在 Angular 5 中做一个计时器 [英] How to do a timer in Angular 5

查看:58
本文介绍了如何在 Angular 5 中做一个计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 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 计时器的方法,如下所示 -

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 中做一个计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆