如何在JavaScript任务队列中将(宏)任务排队? [英] How to queue a (macro)task in the JavaScript task queue?

查看:57
本文介绍了如何在JavaScript任务队列中将(宏)任务排队?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript在浏览器事件循环中排队任务?

不起作用的事情:

  • 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 就是这样做的.

MessagePort.postMessage does just that.

onmessage = e => handleMessage;
postMessage("","*");

如果愿意,您甚至可以使用 MessageChannel 较少干扰的意思:

You can even use a MessageChannel if you want a less intrusive mean:

const channel = new MessageChannel();
channel.port1.onmessage = handleMessage;
channel.port2.postMessage('');

这是目前唯一可以同步执行 任务的API,所有其他API至少暗示着某些并行执行.

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

这篇关于如何在JavaScript任务队列中将(宏)任务排队?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆