2 ms·
I've done some experiments of the form 1. Make a visible change to the DOM, 2. wait somehow for that hopefully to become visible, 3. call a slow compute task
by tzs 8y ago
I've done some experiments of the form
1. Make a visible change to the DOM,
2. wait somehow for that hopefully to become visible,
3. call a slow compute task
I tried the following methods for waiting:
1. setTimeout (various values)
2. window.requestAnimationFrame
3. windows.requestIdleCallback
4, 5, 6. doubled forms of the above three methods. By doubled I mean that instead of, say, calling the slow function from the requestAnimationFrame callback, that callback does another requestAnimationFrame, and it is the callback for that second requestAnimationFrame.
Here is a test program that puts up a page with a count on top, a couple fields to give the timeout for setTimeout and how slow the slow task should be, and buttons to try the aforementioned delay methods (also one to call direct without a delay). Clicking the button will increment the counter, invoke the delay, and then invoke the slow function. It also prints timing information on when various events happened and when various things were called (overwritten for each test), and also a log below that of events and slow task timing.
https://pastebin.com/n26iVs7d https://pastebin.com/n26iVs7d
Results follow.
=== Firefox 62.0 (Mac, Windows)
Double requestAnimationFrame and double requestIdleCallback seem to be reliable. I've never seen the slow task start before the counter display has updated.
Single requestAnimationFrame and requestIdleCallback usually run the slow task before the counter display has updated, but every so often the display updates first. On Windows, single requestIdleCallback seems more likely to do the update first than on Mac.
setTimeout(0) seems to always runs the slow task before the display updates.
Double setTimeout(0) is similar to single requestAnimationFrame or requestIdleCallback. Mostly does not update until after the slow task, but occasionally does update first.
=== Chrome 68.0.whatever_is_current (Mac)
setTimeout(0) seems to always update display before running slow task.
Single requestIdleCallback, same as setTimeout(0).
Single requestAnimationFrame seems to always run the slow task before display update.
Double requestAnimationFrame seems to always update the display before the slow task.
=== Safari (Mac)
setTimeout(0) and single requestAnimationFrame update display before slow task. Does not have requestIdleCallback.
=== Edge (Windows)
No requestIdleCallback.
setTimeout(0) and single requestAnimationFrame seem to always update display before slow task runs.
Looks like double requestAnimationFrame is the way to go.