Shipmind Labs

A live region's clear timer is not a debounce

· 8 min read

An ARIA live region has to be emptied again once a message has been read, and that means a timer. The obvious timer is a debounce: every new write cancels the pending clear and starts a fresh one. For a live region that is the wrong primitive, and it fails in exactly the case that matters most. Under a steady stream of writes the first message stays on screen and nothing behind it is ever announced.

We hit this building liveregion, our React binding for screen-reader announcements. The queue was already correct: messages in order within a politeness, assertive ahead of polite, a repeat made distinct so it is read again. The timing was not. This is the part of that work we would explain to anyone writing their own.

Debounce collapses a burst; a live region must un-collapse one#

A debounce exists to turn many events into one. Resize, scroll, search-as-you-type: the thing being deferred is the work, and dropping all but the last event is the point.

A live region is the opposite problem. Collapsing is what the platform already does to you: the region's text is replaced, the screen reader announces what it finds when it looks, and two messages written in the same frame become one announcement, the second one. The queue exists precisely to undo that, by delivering each message with a gap so all of them are read.

So a debounced clear re-introduces the bug from the other end. Take a filter that announces its result count as you type. Each keystroke queues a message. With a debounced hold, each keystroke also pushes the clear back, so the region keeps showing the first count for as long as you keep typing, and the counts behind it sit in the queue. When typing stops, the drain finally starts and you are read a backlog of counts that are all stale except the last. The region was busy the whole time and said nothing useful.

In code, the tempting version is small, which is probably part of why it gets written:

typescript
// Not what we ship: a debounced hold on top of an otherwise correct queue.
announce(message: string, politeness: Politeness = "polite"): void {
  this.#queue.announce(message, politeness);
  this.#repaint();
  this.#cancel(); // throw away the hold in progress
  this.#arm();    // and hand the showing message a fresh one
}

The arrivals are what must wait. The clearing must not.

Arm a timer only when a message is showing and none is armed#

The whole rule lives in one private method. Driver owns the library's only timer, and #pump is the only thing that creates one:

typescript
#pump(): void {
  if (this.#stopped) return;
  if (!this.#queue.current) return;
  if (this.#timer !== null) return;
  this.#timer = setTimeout(() => {
    this.#timer = null;
    this.#queue.advance();
    this.#repaint();
    this.#pump();
  }, this.#queue.clearAfterMs);
}

Three early exits, in that order, and each one is a bug we would otherwise have shipped.

#stopped is set by stop, so a driver whose host has unmounted arms nothing further.

!this.#queue.current means nothing is showing, so a drain would have nothing to clear. This matters because the queue ignores an empty or whitespace-only message entirely, it is not queued at all. If a blank announce armed a timer anyway, the next real message would be cleared when that earlier timer fired, after a fraction of its own hold.

this.#timer !== null is the thesis. A drain is already armed, so leave it alone. Resetting the timer on every announce would let a steady stream of messages keep the current one on screen for ever while the queue starves behind it.

The handler is the loop#

The timer does not just clear the region; it advances the queue and re-arms itself. The handler nulls #timer first, so the #pump call at the end of the same handler sees an empty slot rather than a handle for a timeout that has already fired. Then advance promotes the next announcement, #repaint paints it, and #pump arms the next hold.

The chain therefore runs once per message and ends on its own: when advance returns null, #repaint paints both regions blank and #pump takes its second early exit. #repaint writes both regions every time (the text in the one matching the current politeness, an empty string in the other) because a region's politeness is read when the page loads, not when its text changes, so there are two regions and the message goes to the right one.

The consequence is the property we wanted. Every message holds the region for exactly clearAfterMs, which defaults to DEFAULT_CLEAR_MS of 1000 ms. The gap between two messages is the hold, so there is no separate inter-message delay to tune and no way for the two to drift apart.

Which leaves announce with nothing to do about timing at all:

typescript
announce(message: string, politeness: Politeness = "polite"): void {
  this.#queue.announce(message, politeness);
  this.#repaint();
  this.#pump();
}

It repaints before pumping because the queue advances immediately when nothing is current, so the first message of an idle queue is painted without waiting for a tick. The #pump that follows then arms that message's hold. A second announce arriving while a message is showing runs the very same three lines and changes nothing about the hold already running.

The test for the idle case pins both halves:

typescript
test("start arms nothing when no message is showing", (t) => {
  t.mock.timers.enable({ apis: ["setTimeout"] });
  const { driver, painted, regions } = driverUnderTest();

  driver.start();
  const paints = painted.length;
  t.mock.timers.tick(5000);
  assert.equal(painted.length, paints, "an empty queue needs no drain");

  driver.announce("Saved");
  t.mock.timers.tick(999);
  assert.deepEqual(regions(), ["Saved", ""], "so the first message gets its full hold");
  t.mock.timers.tick(1);
  assert.deepEqual(regions(), ["", ""]);
});

What may shorten a hold#

One caller-facing method, and one lifecycle method.

typescript
clear(): void {
  this.#queue.clear();
  this.#cancel();
  this.#repaint();
}

stop(): void {
  this.#cancel();
  this.#stopped = true;
}

start(): void {
  this.#stopped = false;
  this.#pump();
}

clear is the only path that cuts a showing message short, and it does that because the host asked explicitly (a route change, a dialog closing). stop cancels and forgets: a cleanup that only called clearTimeout and left the handle in place made the next run of the effect see a drain that no longer existed, and the region kept its text until something called clear. start resumes by pumping, which arms a hold only if a message is still showing. Both the hook and the provider call nothing but start and stop from their effect, so a StrictMode remount, an <Activity> hidden and shown again, or Fast Refresh resumes the same queue, and anything announced in between is still read.

Changing the hold belongs to the same family. setClearAfterMs reaches the one queue and applies from the next drain the driver arms. The drain already running keeps the length it was armed with, because re-arming it would either cut the showing message short or hand it a second full hold, and a host that changed an option on a later render asked for neither:

typescript
driver.announce("A");
driver.announce("B");
driver.announce("C");

t.mock.timers.tick(500);
driver.setClearAfterMs(3000);

t.mock.timers.tick(499);
assert.deepEqual(regions(), ["A", ""], "the drain already armed keeps its length");
t.mock.timers.tick(1);
assert.deepEqual(regions(), ["B", ""], "so A is replaced at 1000 ms");

What it costs to run#

At most one pending timeout per queue, and one queue per page if the queue is placed above the messages with AnnouncerProvider rather than letting two components each build their own. There is no bookkeeping beyond a nullable handle and a stopped flag.

The real cost is latency, and it is worth naming rather than hiding: a message queued behind n others waits n holds before it is read, so at the default a backlog of five polite messages is five seconds deep. Not resetting the timer does not make a flood cheap; it makes it bounded and ordered instead of indefinitely stalled. Two mitigations are already in the design. An assertive message is placed after the last waiting assertive one and ahead of every waiting polite one, so the case that cannot wait (something has gone wrong right now) does not pay for the counts in front of it. And a host that knows its messages are short can lower clearAfterMs, which is validated where it is given: a finite 1 to MAX_CLEAR_MS, so NaN, zero and Infinity are a RangeError naming the option and the value rather than a region that empties before anyone reads it.

The design also makes the awkward part cheap to test. Because the timer lives in a plain class driven by a paint callback rather than in a ref inside a hook, every rule above is checked with mock timers and a recording paint function, with no renderer involved.

The general shape is worth keeping: when a stream of events arrives faster than the sink can drain it, decide whether you are deduplicating the events or delivering all of them. Debounce answers the first question. A queue with a self-re-arming hold answers the second, and a live region is the second one.

Was this useful?

Building something similar?

or email hello@shipmindlabs.com