如何使用RxJS Observables设置倒数计时器? [英] How to make countdown timer with RxJS Observables?

查看:715
本文介绍了如何使用RxJS Observables设置倒数计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用Observables创建倒数计时器,这些示例位于 http://reactivex .io/documentation/operators/timer.html 似乎不起作用.在此特定示例中,与timerInterval相关的错误不是从计时器返回的Observable的函数.

I'm struggling to create a countdown timer using Observables, the examples at http://reactivex.io/documentation/operators/timer.html do not seem to work. In this specific example the error related to timerInterval not being a function of the Observable returned from timer.

我也一直在尝试其他方法,而我想出的最好的方法是:

I have also been experimenting with other approaches and the best I've come up with is:

Observable.interval(1000).take(10).subscribe(x => console.log(x));

这里的问题是它从0到10递增计数,我想要一个倒数计时器,例如10,9,8 ... 0.

The problem here is it counts up from 0 to 10 and I want a countdown timer e.g. 10,9,8...0.

我也尝试过此操作,但是对于Observable类型,timer不存在

I've also tried this but the timer does not exist for type Observable

Observable.range(10, 0).timer(1000).subscribe(x => console.log(x));

以及,它根本不产生任何输出.

As well as, which produces no output at all.

Observable.range(10, 0).debounceTime(1000).subscribe(x => console.log(x));

为澄清起见,我需要有关ReactiveX的RxJS实现而不是MircoSoft版本的帮助.

To clarify I need help with ReactiveX's RxJS implementation, not the MircoSoft version.

推荐答案

您在正确的轨道上-问题是timer在原型上(因此在Observable.range()上)不存在,但在Observable上不存在(请参见RxJS 文档). IE. jsbin

You were on the right track - your problem was that timer does not exist on the prototype (and thereby on Observable.range())but on Observable (see the RxJS docs). I.e. jsbin

const start = 10;
Rx.Observable
  .timer(100, 100) // timer(firstValueDelay, intervalBetweenValues)
  .map(i => start - i)
  .take(start + 1)
  .subscribe(i => console.log(i));

// or
Rx.Observable
  .range(0, start + 1)
  .map(i => start - i)
  .subscribe(i => console.log(i));

这篇关于如何使用RxJS Observables设置倒数计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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