Dina fills the prize envelopes in idle time: a real requestIdleCallback, timeRemaining() and didTimeout read from its deadline, with the field still, racing…
Why it matters
Work that is not urgent (sending analytics, preparing data, filling a cache) should never take time from clicks and frames. An idle callback puts it in breaks that are really empty, as long as you respect the deadline and give a timeout when the work must get done.
The key idea
Idle time is given by the browser, not promised
Common mistakes
Why does requestIdleCallback never run? On a page whose main thread is always full there is no idle time, so the callback waits on. Do not use it for anything urgent; for what must get done, give { timeout } and do only a little when didTimeout is true, because timeRemaining() is 0 then.
Still janky though it uses requestIdleCallback A browser does not stop a callback past its deadline. One step longer than timeRemaining() makes the next frame late. Split the work into small steps and check deadline.timeRemaining() before each one.
Why does a DOM update inside an idle callback cause reflow? An idle callback runs after the frame has been laid out. Writing the DOM there dirties layout again, and reading a size after it forces layout right then, outside timeRemaining()’s count. Collect the results in the idle callback, then write once in requestAnimationFrame.
Try it in this playground
Fill the envelopes with the field still See its largest timeRemaining().
Then with a race on A break is only what is left of each frame.
A packed field, then a 500 ms timeout Without a timeout, the callback waits for the race to end.
Split the big envelopes into 0.5 ms steps The same work, no callback overruns.