setTimeout设置为0的意义

今天再看 Promise 代码时,有个地方用到了setTimeOut函数,但是第2个参数设为0,顿时懵逼了,这是啥意思?

1  function resolve(newValue) {
2         value = newValue;
3         state = 'fulfilled';
4         setTimeout(function () {
5             callbacks.forEach(function (callback) {
6                 callback(value);
7             });
8         }, 0);
9  }

于是百度了一下,自己理解如下 就是将同步代码转异步代码,setTimeout(fn, 0)的作用它可以将最后两个语句添加到运行队列的队尾,并保证在浏览器处理完其他事件之后再运行最后这两个语句。

alert(1);
setTimeout(function(){alert(2); }, 0); 
alert(3);
setTimeout(function(){alert(4); }, 0);
setTimeout(function(){alert(5); }, 0);
setTimeout(function(){alert(6); }, 0); 
alert(7);

这样的输出结果是 
先是1,3,7 这是一定的 然后2,4,5,6这个是不规律乱序的 
因为2456的代码被异步执行了。

参考:

https://www.zhihu.com/question/55050034/answer/158127840

https://www.cnblogs.com/silin6/p/4333999.html

http://www.mamicode.com/info-detail-1106724.html

猜你喜欢

转载自www.cnblogs.com/loveyouyou616/p/9034672.html