The HTML event loop runs one task at a time and lets the browser choose which queue to serve, but a page had no way to say which of its tasks matter more. The Prioritized Task Scheduling API adds that.
scheduler.postTask(callback, options) queues a task and returns a promise for the callback's return value (rejected if it throws or is aborted). Options:
priority:"user-blocking"(work the user is waiting on),"user-visible"(the default) or"background"(logging, prefetching).signal: anAbortSignalto cancel, or aTaskSignalfrom aTaskController, whosesetPriority()moves pending tasks to a new priority and firesprioritychange.delay: milliseconds to wait before queueing.
Among scheduler tasks, the highest priority runs first and ties go to the oldest. How they interleave with timers, messages, input and rendering is up to the browser; the spec suggests running background only when nothing else is waiting.
await scheduler.yield() splits a long task. The rest of the function becomes a continuation task, so input handling and rendering get a turn first. Unlike setTimeout(fn, 0), the continuation:
- runs one step above tasks of the same priority, so work queued meanwhile doesn't jump ahead;
- inherits the priority and abort signal of the
postTask()task it came from (user-visibleotherwise); - isn't a timer, so no nesting clamp or hidden-page timer throttling (a
delayoption is a timer, though).
Before this API, libraries yielded with a MessageChannel message: no clamp, but no priority either, so the continuation waits its turn like any other task.
Support: Chrome 94 and Firefox 142 (yield() since Chrome 129); Safari has neither. Feature-detect with 'scheduler' in globalThis and fall back to setTimeout. Work that is CPU-bound rather than input-bound belongs in a worker instead.