详解JavaScript事件循环机制

原创 Fly丶 教程 js 54阅读 2018-11-11 16:11:13 举报

众所周知,JavaScript 是一门单线程语言,虽然在 html5 中提出了 Web-Worker ,但这并未改变 JavaScript 是单线程这一核心。可看HTML规范中的这段话:

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. There are two kinds of event loops: those for browsing contexts, and those for workers.

为了协调事件、用户交互、脚本、UI 渲染和网络处理等行为,用户引擎必须使用 event loops。Event Loop 包含两类:一类是基于 Browsing Context ,一种是基于 Worker ,二者是独立运行的。 下面本文用一个例子,着重讲解下基于 Browsing Context 的事件循环机制。

来看下面这段 JavaScript 代码:

```console.log('script start');

setTimeout(function() {
console.log('setTimeout');
}, 0);//前端全栈交流学习圈:866109386
//帮助1-3年前端人员,突破技术,提升思维
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});

console.log('script end');

console.log('script start');

setTimeout(function() {
console.log('setTimeout');
}, 0);//前端全栈交流学习圈:866109386
//帮助1-3年前端人员,提升技术,突破思维
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});

console.log('script end');

console.log('script start');

setTimeout(function() {
console.log('timeout1');
}, 10);

new Promise(resolve => {
console.log('promise1');
resolve();
setTimeout(() => console.log('timeout2'), 10);
}).then(function() {
console.log('then1')
})

console.log('script end');

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复