js中特殊的宏任务小白指南_任务使用帮助

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

js中特殊的宏任务小白指南

一.setImmediate

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

js中特殊的宏任务小白指南_任务使用帮助

立即触发回调函数,使其进入宏任务队列(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
海计划公众号
(0)
上一篇 2020/03/23 18:37
下一篇 2020/03/23 18:37

您可能感兴趣的内容