Last updated: Apr 12, 2024
Manually defer code execution by briefly interrupting your work to give the browser opportunities to run more important tasks.
// https://web.dev/articles/optimize-long-tasks#defer-code-execution export const yieldToMain = async (callback: () => void) => { if (globalThis?.scheduler?.yield) { await globalThis.scheduler.yield(); } else { await new Promise((resolve) => setTimeout(resolve, 0)); } callback(); }; // Usage async function runJobs(jobQueue: (() => void)[]) { for (const job of jobQueue) { // Run the job: job(); // Yield to the main thread: await yieldToMain(); } }