實驗證明,setTimeout任務永遠在普通任務後面執行,當執行一個較爲久的任務時可以將其放入到setTimeout()中,讓其延後執行
function a(){
setTimeout(function(){
alert("定時器任務");
},0);
sleep(5000);
alert("普通任務");
}
a();
function sleep(ms) {
var start = new Date();
while (new Date() - start <= ms) {}
}
下面更加助於理解的一個例子:
function a(){
setTimeout(function(){
console.log("定時器任務2"+ new Date());
},10000);
setTimeout(function(){
console.log("定時器任務1"+ new Date());
},5000);
console.log("start "+ new Date());
sleep(5000);
console.log("普通任務"+ new Date());
}
a();
function sleep(ms) {
var start = new Date();
while (new Date() - start <= ms) {}
}
結果如下:
換一下順序:
function a(){
setTimeout(function(){
console.log("定時器任務1"+ new Date());
},5000);
console.log("start "+ new Date());
sleep(5000);
console.log("普通任務"+ new Date());
setTimeout(function(){
console.log("定時器任務2"+ new Date());
},10000);
}
a();
function sleep(ms) {
var start = new Date();
while (new Date() - start <= ms) {}
}
結果爲:
這就好理解了,程序還是按順序執行的,只不過遇到setTimeout時,等待設定的時間後,看隊列中有沒有在執行的任務,如果沒有,則加入隊列,並執行,如果有,則等待隊列中的任務執行完了在加入執行。