zoukankan      html  css  js  c++  java
  • js中特殊的宏任务

    一.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
  • 相关阅读:
    SQL 语言入门
    [转载]Sql Server 中的Login,Schema,User,Role之间的关系
    稀疏矩阵运算
    特征缩放的几种方法
    dp解出栈序列数
    神经网络解决多分类问题例:数字识别
    多分类例题
    fminunc 函数的用法
    二分类
    特征归一化、特征映射、正则化
  • 原文地址:https://www.cnblogs.com/lyraLee/p/11832716.html
Copyright © 2011-2022 走看看