js中特殊的宏任务

摘要:目前只有IE10+和NodeJS支持该API。立即触发回调函数,使其进入宏任务队列(macro task queue),比setTimout(fn, 0)的执行顺序要快,性能也更高。因为setTimeout(fn,0)实质上会有4ms的延迟。

一.setImmediate

目前只有IE10+和NodeJS支持该API。

立即触发回调函数,使其进入宏任务队列(macro task queue)

语法:

// 只有一个参数
setImmediate(callback)

比setTimout(fn, 0)的执行顺序要快,性能也更高。因为setTimeout(fn,0)实质上会有4ms的延迟。


二. MessageChannelAPI

1. 作用

MessageChannelAPI允许我们新建一个消息通道,并通过它的两个属性port1和port2进行通信。

实质是通过一个端口发送数据,另一个端口通过onmessage监听另一个端口发送的数据。

触发方式:

同步触发,即port发送数据时立即触发。所以会比setTimeout(fn,0)触发要早。


2. 使用

MessageChannel是个构造函数。使用前需要创建实例,生成一条消息通道。

const channel = new MessageChannel();

实例自带两个端口,即消息通道的两端

const port1 = channel.port1;
const port2 = channel.port2;

示例:(模拟setimmediate)

const channel = new MessageChannel();
const port1 = channel.port1;
const port2 = channel.port2;
port1.onmessage = function(e) {
  console.log(e.data);
}
setTimeout(function() {
  console.log(‘settimeout‘); //4ms
})
port2.postMessage(‘hello world‘);  //立即
Promise.resolve().then(() => {
  console.log(‘then‘); // 微任务
})
// 运行结果
then 
hello world
settimeout


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_6381