https://blog.csdn.net/SemineLee/article/details/87215457
event loop即事件循环,是指浏览器或Node的一种解决javaScript单线程运行时不会阻塞的一种机制,也就是我们经常使用异步的原理。
例子
下面的按钮,按钮点击调用和,代码调用效果是不一样的。
<div id="btn">
按钮
</div>
<script>
var btn = document.getElementById("btn");
btn.addEventListener("click", () => {
Promise.resolve().then(() => console.log("Microtask1"))
console.log("listener 1")
});
btn.addEventListener("click", () => {
Promise.resolve().then(() => console.log("Microtask2"))
console.log("listener 2")
});
btn.click()
</script>
相关文章
题目
代码输出结果1
const first = () => (new Promise((resovle, reject) => {
console.log(3);
let p = new Promise((resovle, reject) => {
console.log(7);
setTimeout(() => {
console.log(5);
resovle(6);
}, 0)
resovle(1);
});
resovle(2);
p.then((arg) => {
console.log(arg);
});
}));
first().then((arg) => {
console.log(arg);
});
console.log(4);
代码输出结果2
function test() {
console.log(1)
setTimeout(function () { // timer1
console.log(2)
}, 1000)
}
test()
setTimeout(function () { // timer1
console.log(3)
})
new Promise(function (resolve) {
console.log(4)
setTimeout(function () { // timer1
console.log(5)
}, 100)
resolve()
}).then(function () {
setTimeout(function () { // timer1
console.log(6)
}, 0)
})
console.log(8)
看代码说出结果3
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
async1();
new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
});
console.log('script end');
看代码输出结果4
setTimeout(() => {
console.log(7);
});
Promise.resolve()
.then(() => {
console.log(0);
return Promise.resolve(4);
})
.then((res) => {
console.log(res);
});
Promise.resolve()
.then(() => {
console.log(1);
})
.then(() => {
console.log(2);
})
.then(() => {
console.log(3);
})
.then(() => {
console.log(5);
})
.then(() => {
console.log(6);
});
看代码输出结果5
console.log(1);
Promise.resolve().then(() => {
console.log(2)
return Promise.resolve(3)
}).then(res => {
console.log(res);
})
console.log(4)
new Promise((reslove, reject) => {
console.log(5)
reslove()
}).then(() => {
console.log(6)
})
console.log(7)