setTimeout在普通任務後面執行

實驗證明,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時,等待設定的時間後,看隊列中有沒有在執行的任務,如果沒有,則加入隊列,並執行,如果有,則等待隊列中的任務執行完了在加入執行。



發佈了20 篇原創文章 · 獲贊 2 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章