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

前端 未结 1 470
迷失自我
迷失自我 2021-01-03 12:30

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:

相关标签:
1条回答
  • 2021-01-03 12:51

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

    0 讨论(0)
提交回复
热议问题