HtmlScheduler unstable
A Scheduler for the browser, which keeps fiber work from holding up the page's rendering and input.
Constructors
Makes a Scheduler that runs fiber work in time slices, in browser tasks.
When to use
Use to run Effects in the page outside BrowserHost.mount, which uses one
when the caller hasn't provided a Scheduler.
Details
Every fiber shares one queue. A task runs queued fiber work until budget
is spent, then leaves the rest for the next task, so the browser can render
and handle input in between. A fiber running when the task's budget runs
out yields, as it does after Scheduler.MaxOpsBeforeYield operations.
Work queued during a task runs in the next one. A fiber resumed outside a
task of this Scheduler, by a fetch for example, runs in what is left of
the last budget. Once that is spent it starts a budget of its own, unless
fiber work is already waiting for a task, in which case it joins that work.
Tasks are posted with scheduler.postTask where the browser has it,
MessageChannel otherwise, and setTimeout in environments that have
neither.
Lower priorities run first, and equal ones in the order they were queued.
Effect queues everything at priority 0, and Effect.yieldNowWith(priority)
moves a fiber to another priority. The sign picks how the work competes
with the page:
| Priority | Runs | postTask priority |
|---|---|---|
| below 0 | before other fiber work | "user-blocking" |
| 0 | in order | "user-visible" |
| above 0 | only when no other fiber work is queued | "background" |
A fiber that yields because the budget ran out resumes at the priority it
was queued at. So yield* Effect.yieldNowWith(1) keeps CPU-bound work in
the background until the fiber next waits on something or yields
explicitly, after which it is back at 0. Fibers it forks or wakes start
at 0.
Gotchas
A single synchronous step can't be split: an Effect.sync that runs for
200 milliseconds blocks the page for 200 milliseconds. Move such work to a
Worker. Background work runs only when nothing else is queued, so it
waits for as long as other fiber work keeps arriving.
Signature
declare function make(options?: Options): SchedulerExample Indexing in the background
import { HtmlScheduler } from "effect/ui/html"import { Effect } from "effect"
declare const documents: ReadonlyArray<string>declare const index: (document: string) => Effect.Effect<void>
const reindex = Effect.gen(function*() { yield* Effect.yieldNowWith(1) for (const document of documents) yield* index(document)})
Effect.runFork(reindex.pipe(Effect.provide(HtmlScheduler.layer())))