What is the most straight-forward and direct way to queue a task in the browser event loop, using JavaScript?
Things that don't work:
window.setImmediate(func)
: Non-standard.window.setTimeout(func, 0)
/window.setInterval(func, 0)
: Browsers throttle timers to ≥ 4ms.new Promise(r => r()).then(func)
: That queues a microtask, not a task.MessagePort.postMessage
does just that.
onmessage = e => handleMessage;
postMessage("","*");
You can even use a MessageChannel if you want a less intrusive mean:
const channel = new MessageChannel();
channel.port1.onmessage = handleMessage;
channel.port2.postMessage('');
This is currently the only API that does queue a task synchronously, all others implying at least some in parallel execution.
Maybe one day we will have a scheduler.postTask
method, which would even allow us to specify some priority for our tasks, but that's for the future only...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With