1.
setTimeout(function() {
console.log('1')
});
new Promise(function(resolve) {
console.log('2');
resolve();
}).then(function() {
console.log('3')
});
console.log('4');
輸出結果:2,4,3,1
2.
setTimeout(function(){
console.log('定時器開始啦')
});
new Promise(function(resolve){
console.log('馬上執行for循環啦');
for(var i = 0; i < 10000; i++){
i == 99 && resolve();
}
}).then(function(){
console.log('執行then函數啦')
});
console.log('代碼執行結束');
輸出結果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SOxAjM4YDNzkTZzIDZ1QmYyYzX1UTMyYTMwMzLcZDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
3.
$.ajax({
type: "get",
dataType:'jsonp',
url:'https://ipinfo.io',
success:() => {
console.log('發送成功!');
}
})
console.log('代碼執行結束');
輸出結果:
4.
function sleep(delay) {
var start = (new Date()).getTime();
while ((new Date()).getTime() - start < delay) {
continue;
}
}
console.log(new Date)
setTimeout(() => {
console.log('延時并不是三秒3秒, 而是5秒')
console.log(new Date)
},3000)
sleep(5000)
輸出結果:
除了廣義的同步任務和異步任務,我們對任務有更精細的定義:
- macro-task(宏任務):包括整體代碼script,setTimeout,setInterval
- micro-task(微任務):Promise,process.nextTick
5.
console.log('1');
setTimeout(function() {
console.log('2');
new Promise(function(resolve) {
console.log('4');
resolve();
}).then(function() {
console.log('5')
})
})
new Promise(function(resolve) {
console.log('7');
resolve();
}).then(function() {
console.log('8')
})
setTimeout(function() {
console.log('9');
new Promise(function(resolve) {
console.log('11');
resolve();
}).then(function() {
console.log('12')
})
})
輸出結果: