【问题标题】:How can I create a countdown timer with RXJS in angular?如何使用 RXJS 以角度创建倒数计时器?
【发布时间】:2017-06-29 08:43:43
【问题描述】:

我正在 angular2 中构建一个倒数计时器,计时器可观察(没有找到任何其他使用 angular2 的解决方案)。

计时器从 15:00 分钟开始,一直到 00:00。我面临的问题是,起初计时器正在减少 1 秒,但随着时间流逝到秒数,差距会增加。

在 14:00 -13:00 与我手机上的秒表运行的计时器相比,有 2-3 秒的差距。这一秒差距逐渐增加,直到达到 00:00 时差为 3-4 分钟,即计时器运行时间超过 15:00 分钟。

另外,如果我切换标签,差距会增加,倒计时到 15:00 分钟可能需要 30 分钟或 1 小时。

import {Observable} from "rxjs/Rx";
import { Subscription } from "rxjs/Subscription";

public timer = Observable.timer(1000, 1000);
public startTime = 900;
  public timerfunction(): void {
           if ( this.counter < 10) {
           this.timerSubs = this.timer.subscribe((tt) => {
            //  console.log("inside timer" + this.counter);
             this.timerfunc(tt);
            });
           this.unsubscribeTimer();
          }
           this.counter = this.counter + 1;
  }
​public timerfunc(tt: number){
{ console.log("Timer ticks" + " : " + tt); 
  if (tt < this.startTime && tt !== 0) {
      if (tt % 60 === 0 && tt !== 0 && this.minutes !== 0) {
     // console.log("t" + tt + this.minutes + ":" + this.seconds );
     this.minutes = this.minutes - 1;
     this.seconds = 59;
    // console.log(this.startTime + "start time");
    }else {
     // console.log( "this.seconds ----- fucTTT" + this.seconds );
      if (this.seconds !== 0) {
      this.seconds = this.seconds - 1;
      } else if (this.seconds === 0 && this.minutes !== 0) {
        this.seconds = 59;
        this.minutes = this.minutes - 1 ;
      //  console.log("inside this loop");
      }
      // console.log("minutes" + this.minutes + "seconds" + this.seconds);
    }
  }}

【问题讨论】:

  • 问题的上下文很清楚,但请将帖子的标题和结尾改为真正一个问题。您想了解/获得什么帮助?
  • 我想知道这个问题的解决方法。为什么会出现这种差异??
  • 尝试做 setTimeout(()=> {this.timerfunc(tt);});将处理执行移出订阅

标签: angular rxjs countdowntimer


【解决方案1】:

这是一个倒数计时器的简单实现:

import { interval } from 'rxjs'
import { map, take } from 'rxjs/operators'

const duration = 15 * 60 // 15 minutes

interval(1000).pipe(take(duration), map(count => duration - count)).subscribe(seconds => {
  console.log(seconds);
})

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
相关资源
最近更新 更多