RxJS timeInterval() Utility Operator

RxJS timeInterval() operator is a utility operator used to emit an object that contains the current value and the time that has passed between emitting the current value and the last value calculated using scheduler input taken. It retrieves the current time at each emission and then calculates the difference. The time interval is calculated in milliseconds.

In other words, we can say that the RxJS timeInterval() operator intercepts the items from the source observable and emits in their place objects that indicate the amount of time that elapsed between pairs of emissions.

Syntax:

Following is the syntax of the RxJS timeInterval() utility operator:

timeInterval(scheduler): Observable timeInterval<T>(scheduler: SchedulerLike = async): OperatorFunction<T, TimeInterval<T>>

Parameter Explanation

  • scheduler: This is an optional argument used to calculate the time elapsed between the current and previous value from source observable. Its default is async.
  • Return value

    The RxJS timeInterval() operator's return value is an observable that has source values and the time interval and emits infomation about value and interval.

    Let us see some examples of the RxJS timeInterval() operator to understand it clearly.

    Example

    import { of } from 'rxjs'; import { filter, timeInterval } from 'rxjs/operators'; let list1 = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); let final_val = list1.pipe(timeInterval()); final_val.subscribe(x => console.log(x));

    Output:

    After executing the above example, you will see the following result:

    Example2 (Time between mouse clicks)

    import { fromEvent } from 'rxjs'; import { timeInterval, tap } from 'rxjs/operators'; fromEvent(document, 'mousedown') .pipe(timeInterval(), tap(console.log)) .subscribe( (document.body.innerText = `Time since last click (in milliseconds): ${i.interval}`)

    Output:

    After executing the above example, you will see the following result:

    Next Topic RxJS Operators