Debounce a stream of events
Debounce a stream of events in JavaScript with an async generator: yield the latest value only after a quiet period. Node.js 24.
Debouncing a stream means yielding the latest value only when no new value has arrived for a while. As an async generator it works on any async iterable.
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
async function* debounceStream(source, ms) {
const iterator = source[Symbol.asyncIterator]();
let pending = iterator.next();
let latest;
let hasLatest = false;
while (true) {
const result = hasLatest
? await Promise.race([pending, delay(ms).then(() => 'quiet')])
: await pending;
if (result === 'quiet') {
yield latest;
hasLatest = false;
continue;
}
if (result.done) {
if (hasLatest) yield latest;
return;
}
latest = result.value;
hasLatest = true;
pending = iterator.next();
}
}
async function* keystrokes() {
const typed = [['h', 10], ['he', 10], ['hel', 80], ['hell', 10], ['hello', 0]];
for (const [text, wait] of typed) {
yield text;
await delay(wait);
}
}
for await (const text of debounceStream(keystrokes(), 40)) console.log(text);hel
helloThree keystrokes arrive within 20 ms, and then the source goes quiet for 80 ms, longer than the 40 ms window, so hel is yielded. The last two arrive close together, and the final value is flushed when the source ends. Every value that was replaced before a pause is dropped.
Each loop round leaves a short timer behind, which is harmless here. For a hot source, clear the timer or use an AbortSignal with the delay.