Background work in Javascript
I’m writing a little browser toy where I calculate a model in the background and render it frequently. Think something like an animated cellular automaton.
Rendering is easy in modern browsers: you just use requestAnimationFrame and hopefully it’ll call your code once per screen refresh or at least as fast as it can manage.
But how do you do background compute work in Javascript in 2023? I want it to run as fast as possible (ie, 100% CPU for the browser tab) but still be smooth and responsive. I think the right answer is “web workers” but then that requires the overhead of passing the calculations back and forth via messages (and JSON serialization?!).
Here’s some other things I tried for background Javascript work. I tested using a calculate function which executes in well under 1ms.
- Use
setIntervalto fire off the calculation: 4ms is the minimum allowed in modern browsers, limiting you to 250 calculations / second. - Use a spin loop. This works and I can do but now the main browser thread is blocking everything and it’s a UI disaster. Not feasible.
- Use a spin loop with a Promise to yield via a short sleep. Still subject to 4ms on
setTimeout, but overhead means it’s more like 5.2ms in practice. - Use
requestIdleCallback. I had high hopes for this but in practice I’m getting called every 11.1ms or 90 updates / second. Turns out that’s my screen refresh rate and the idle callback rate changes if I update the display driver refresh. It’s like VBlank interrupts in 2023 only about nineteen layers removed from the hardware.
I think in practice setInterval will work for me; my calculations are likely to take a few milliseconds and anyway I don’t want it to run “too fast” because it won’t be visible. Still kinda wacky this is so hard in 2023. Web workers are probably the right way if I need faster than 4ms.
// Calculation loop using idle callbacks
function calculate_idle() {
calculate();
window.requestIdleCallback(calculate_idle);
}
// Calculation loop using ersatz sleeps. Note 4ms is minimum here.
async function calculate_sleep(interval) {
// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
while (1) {
calculate();
await new Promise(r => setTimeout(r, interval));
}
}
switch (mode) {
case "idle":
// Seems to be every 11ms per quick testing in Chrome
calculate_idle();
break;
case "interval":
// Browsers seem to make 4ms the minimum interval
setInterval(calculate, 1);
break;
case "spin":
while (1) {
calculate();
}
break;
case "sleep":
calculate_sleep(0);
break;
}