// Check for support before using.
if (globalThis.scheduler?.yield) {
console.log("scheduler.yield: Supported");
} else {
console.error("scheduler.yield: NOT Supported");
}Scheduler: yield() method / notebook
Scheduler: yield() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
button.addEventListener("click", async () => {
// Provide immediate feedback so the user knows their click was received.
showSpinner();
await scheduler.yield();
// Do longer processing
doSlowContentSwap();
});checkbox.addEventListener("change", async () => {
await scheduler.yield();
doSlowContentFiltering();
});function doWork(value) {
console.log(`work chunk ${value}`);
}
const workList = [0, 1, 2, 3, 4];
for (const work of workList) {
doWork(work);
await scheduler.yield();
}scheduler.postTask(() => console.log("user-visible postTask"));
scheduler.postTask(() => console.log("user-blocking postTask"), {
priority: "user-blocking",
});
await scheduler.yield();
console.log("user-visible yield");async function first() {
console.log("starting first function");
await scheduler.yield();
console.log("ending first function");
}
async function second() {
console.log("starting second function");
await scheduler.yield();
console.log("ending second function");
}
first();
second();async function backgroundWork() {
scheduler.postTask(() => console.log("background postTask"), {
priority: "background",
});
scheduler.postTask(() => console.log("user-visible postTask"), {
priority: "user-visible",
});
// yield() inherits "background" priority from surrounding task.
await scheduler.yield();
console.log("default-background yield");
}
await scheduler.postTask(backgroundWork, { priority: "background" });const taskController = new TaskController();
function firstHalfOfWork() {
console.log("first half of work");
taskController.abort("cancel work");
}
function secondHalfOfWork() {
// Never runs.
console.log("second half of work");
}
scheduler.postTask(
async () => {
firstHalfOfWork();
await scheduler.yield();
secondHalfOfWork();
},
{ signal: taskController.signal },
);