RxJS timer() Creation Operator
RxJS timer() operator is a creation operator used to create an observable that starts emitting the values after the timeout, and the value will keep increasing after each call.
In other words, we can say that the RxJS timer() operator creates an observable that emits one particular item after a given delay or a span of time that we have specified earlier. It is like an RxJS interval() operator, but we can specify when the emissions should start.
Syntax:
Following is the syntax of the RxJS timer() creation operator:
Or
Or
Parameter Explanation
- dueTime: It is used to specify the initial delay time specified as a Date object or as an integer denoting milliseconds to wait before emitting the first value of 0. It can be in milliseconds or date. It is an optional argument. Its default value is 0.
- periodOrScheduler: It specifies the time between emissions of the following numbers. It is also an optional argument. Its default value is undefined.
- scheduler: It specifies the SchedulerLike to use to schedule the emission of values and provide a notion of “time.” It is also an optional argument. Its default value is undefined.
Return value
The RxJS timer() operator returns an observable that emits a 0 after the dueTime and ever-increasing numbers. You can say that it emits the value after the timeout, and the value will keep increasing after each call.
Let us see some examples of the RxJS timer() operator to understand it clearly.
Example 1 (Timer emitting 1 value then complete)
Output:
After executing the above example, you will see the following result:
In the above example, you can see that it has emitted just one value and then get completed, so no second value is emitted.
Example 2 (Timer emitting values after 1 second, then every 2 seconds)
Output:
After executing the above example, you will see the following result:
In the above example, you can see that it has emitted the first value after 1 second and then after every 2 seconds.
Example 3 (Emitting ascending numbers, one every second (1000ms), starting after 10 seconds.)
Output:
After executing the above example, you will see the following result:
In the above example, you can see that it has emitted the first value after 10 seconds, and then after every 1 second, it is emitting the ascending values.