RxJS Crash Course – Create a Timer

0

We can also create a timer by calling observable timer with the number of milliseconds we want to wind it up to start the timer. We just call subscribe on it and then it will emit a value once.

Demo

The timer runs out so we refresh the page and one second later our timer runs out.

If we want a timer that keeps repeating we can use an interval that emits a value after the specified time frame so every 1000 milliseconds we’ll get a new value emitted.

In this case, Here we’ll print out a date with the number of seconds in the minute to show how this works.

Demo

We reload the page and then every second we get a new value emitted from the observable now.

I’m going to show you one last way to create an observable there’s actually more ways than this. But I think this covers the basics for now so we’ll do observable of which allows us to pass any static value we want to be observable.

So we’ll go ahead and pass it a string, array, number, boolean, and an object.

Demo

This example shows how any type of data can be a stream which is an important concept to keep in mind when building reactive software.

Next article:

0