Skip to content

Automatic queue pausing when processing time exceeds threshold #9

@flexsurfer

Description

@flexsurfer

Summary

Implement a mechanism to automatically pause the event queue if its processing time exceeds a given threshold, to improve UI responsiveness and maintain frame budget.

Motivation

Currently, the event queue runs synchronously and processes all pending events in a loop. If a large number of events are queued, this can block the main thread and delay UI updates.

To address this, we want to:

  • Measure the total execution time of the event loop.
  • Automatically yield control back to the browser (via scheduleNextTick or scheduleAfterRender) if processing exceeds a safe time window (e.g. 8–16ms).
  • Resume processing on the next tick.

This ensures smoother rendering and avoids long blocking operations.

Proposed Implementation

  1. In the runQueue() method, track start time using performance.now().
  2. After processing each event, check the elapsed time.
  3. If elapsed time exceeds a predefined threshold (e.g. MAX_QUEUE_TIME_MS), trigger a pause and schedule a resume using yield or flush.

Example

const start = performance.now();
while (this.queue.length > 0) {
  const nextEvent = this.queue[0];
  if (!nextEvent) break;

  this.processFirstEvent();

  const elapsed = performance.now() - start;
  if (elapsed > MAX_QUEUE_TIME_MS) {
    this.fsmTrigger('pause', scheduleNextTick);
    return;
  }
}
this.fsmTrigger('finish-run');

Configurability

MAX_QUEUE_TIME_MS should be configurable

Benefits

  • Prevents long blocking runs of the queue.
  • Improves responsiveness and allows rendering to proceed in time.
  • Plays nicely with scheduling model already implemented via meta (flush, yield, etc).

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions