Now we're going to look at more practical operators. These are especially related to time. It's quite common to need an observable that ticks periodically, for instance, every second or every 100 milliseconds. We're talking about an alternative to setInterval.
Let's start by creating an observable called foo with observable.create such that for each observer that subscribes, we are going to set an interval to run a function, let's say, every one second. Every one second, we're going to deliver a value to the observer.
Which value will we deliver? Let's say we deliver zero. Actually, instead of zero, let's deliver a sequence of values starting at zero, like i is initialized at zero. If we deliver i, it's zero. Then we can increment i. The next time this function runs, i will be one. Next time, it will be two, three, four, etc.
If we run this, we will see after one second the value is zero. Then, every one second, we see the next number. Instead of writing all of this, it would be practical to have a shortcut to making these observables, and there is. There's an operator called interval which takes one argument, which is the period.
If we give 1,000 for one second, we will see the same observable. Interval has internal to it this machinery of remembering the values and incrementing them. We can also change this to make it faster. 100 milliseconds will run faster.
There's something really important to know about interval, is that it sets a separate interval for each observer that subscribes. Let me demonstrate. If I set a timeout to run a function after let's say, one and a half seconds, I am going to subscribe to the same observable.
Remember, because observable executions are not shared like we saw in the beginning of the course, the second observer that subscribes won't see the same numbers at the same time. Let's try that.
We first see zero. Then after one and a half seconds, the other one subscribes. Because it set its own interval, they won't be seeing the same values at the same time. That's always important to keep in mind when dealing with observables and time.
There's also another operator that we can look at, which is called timer. Timer is very similar to interval. Interval took just one argument called period, but timer takes two. It takes the start time, and it takes the period. I can do something like after three seconds, we will start. After we start, every one second we will tick.
If you want, you could for instance, insert your birthday here. Then this observable, foo, will start ticking on your birthday. After that, it will tick every one second. That's how we make observables related to time in RxJS.