How to queue a (macro)task in the JavaScript task queue?

时光总嘲笑我的痴心妄想 提交于 2021-02-16 05:29:58

问题


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.

回答1:


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...



来源:https://stackoverflow.com/questions/61574088/how-to-queue-a-macrotask-in-the-javascript-task-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!