DEV Community

Cover image for RxJS Operators: auditTime
Steven Boyd-Thompson
Steven Boyd-Thompson

Posted on • Originally published at drownedintech.dev

RxJS Operators: auditTime

RxJS is a JavaScript library that enables the creation of asynchronous and event-based programs. The main type is the Observable and a suite of functions and operators are provided to make it easier to work with the data coming through. This series will detail those operators (and a few stand-alone functions) and provide examples of their use.

In this post, we’re going to cover the auditTime operator.

What does it do?

The auditTime operator is similar to the audit operator. Rather than providing an observable to control the handling, we provide a time in milliseconds. When the time has elapsed the last emitted value will be sent through the pipeline.

Example

import { auditTime, interval } from 'rxjs';

interval(1000)
    .pipe(auditTime(5000))
    .subscribe(x => {
        console.log(x);
    });
Enter fullscreen mode Exit fullscreen mode

We’re using interval to send a value through every second. We’ve configured auditTime to only allow a value every 5 seconds. So if we run this we’ll see:

4
9
14
19
24
Enter fullscreen mode Exit fullscreen mode

It’s important to note here that auditTime won’t send out the last value every 5 seconds. The timer only starts when a new value comes in. We can demonstrate this behaviour with a change to the above example. Rather than using interval we’ll create our own subject and send a value out after 10 seconds.

import { Subject, auditTime, interval } from 'rxjs';

const value$ = new Subject<string>();

value$
    .pipe(auditTime(5000))
    .subscribe(x => {
        console.log(x);
    });

setTimeout(() => value$.next('First Value'), 10000);
Enter fullscreen mode Exit fullscreen mode

When we run this we will only see the value logged out after 15 seconds. Calling value$.next('First Value') gave the value to auditTime and started the timer running. Once the 5-second timer on auditTime completed it sent the last (and in this case only) value through the rest of the pipeline.

This behaviour makes this useful when dealing with high-throughput observables that don’t need every value handling. A good example of this is user input. If we’re using RxJS to listen for input into a text field, we don’t want to respond to every keypress as the user is typing. Using auditTime the first keypress will start the timer running and we’ll process the input at regular intervals as the user is still typing.

The source code for this example is available on GitHub:

Top comments (0)