簡體   English   中英

如何使用 RXJS 以角度創建倒數計時器?

[英]How can I create a countdown timer with RXJS in angular?

我正在 angular2 中使用計時器 observable 構建一個倒數計時器(使用 angular2 沒有找到任何其他解決方案)。

計時器從 15:00 分鍾開始,一直到 00:00。 我面臨的問題是,起初計時器減少 1 秒,但隨着時間的推移,差距增加。

在 14:00 -13:00 與我手機上秒表運行的計時器相比,有 2-3 秒的差距。 逐漸地,此秒差距增加,直到達到 00:00,差異為 3-4 分鍾,即計時器運行超過 15:00 分鍾。

此外,如果我切換選項卡,差距會增加,可能需要 30 分鍾或 1 小時才能倒計時到 15:00 分鍾。

 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); } }}

這是一個倒數計時器的簡單實現:

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);
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM