如何在JavaScript任务队列中将(宏)任务排队?

编程入门 行业动态 更新时间:2024-10-13 08:22:45
本文介绍了如何在JavaScript任务队列中将(宏)任务排队?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

不不起作用的事情:

  • window.setImmediate(func) :非标准.
  • window.setTimeout(func,0)/ window.setInterval(func,0):浏览器将计时器的计时器调整为≥4ms.
  • 新的Promise(r => r()).然后(func):将微任务而不是任务排队.
  • 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.

也许有一天我们将有一个 scheduler.postTask 方法,它甚至可以让我们为任务指定一些优先级,但这只是将来的事情.

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任务队列中将(宏)任务排队?

本文发布于:2023-11-23 16:21:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622117.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:队列   中将   如何在   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!