Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

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.

JavaScript
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);
Text
hel
hello

Three 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.

Also inFunctions
Taggednode 24
Share

More snippets

Functions

Memoize a function with a Map

Memoize a function in JavaScript with a Map keyed by its argument, caching results including undefined. For single-argument pure functions on any Node.js.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.