CodePark/ questions / Long tasks & the main thread
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Long tasks & the main thread

What does await scheduler.yield() do better than await new Promise((r) => setTimeout(r, 0)) when you break up a long task?

The rest of your work continues before other waiting tasks, instead of joining the back of the queue

Both give the browser a chance to handle input and paint. After that, scheduler.yield() puts your continuation at the front of the queue. With setTimeout, the rest of your work goes to the back. Other scripts' tasks, like ads or analytics, can run first, so your work can finish much later. Browsers also add a minimum delay to deeply nested setTimeout calls.

"Moves the rest of your function to a background thread" is the tempting wrong answer. It still runs on the main thread. Only Web Workers use another thread. Not every browser supports
scheduler.yield() yet, so check for it and fall back to setTimeout.