Countdown timer using RxJS

Creating a countdown timer with RxJS is pretty simple. The block of code below creates an Observable that when it receives a truthy on the input stream, the countdown will commence emitting the next value in the sequence on every interval until 0 is reached.

Any further truthy values on the input stream will restart the countdown whilst falsey values will cancel the countdown.

Times are based in milliseconds.

Breaking it down

The magic in this stream occurs within the switchMap. When the input stream sends through a truthy value, an Rx timer starts counting incrementing based on the defined interval. This timer continues until the duration has been reached, plus one (to allow the countdown to reach 0 later) e.g. [0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000].

If a falsey value comes through the input stream then switchMap will swap out the timer for an Obversable that will never emit, thus cancelling the countdown.

Finally, the map function inverts the direction of the counting timer so that we get a countdown e.g. [10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 0].

Example

See the example on jsbin.com demonstrating the use of the stream to launch a rocket.
https://jsbin.com/sibacav/edit?js,output

 

The code is written in TypeScript but is easily convertible to JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.