setTimout 0間隔問題

關於 setTimeout 相關的文章:

 

setTimeout ,xhr,event 線程問題


使用 javascript Workers 進行計算


Analyzing Timer Performance


Revenge of the Timers


On JavaScript, EDP, and 0ms timeouts

 

 

總結:

 

1.由於javascript屬於事件驅動編程(EDP Event Driven Programming),運行在瀏覽器中,則同其他 gui 程序一樣要依賴於事件隊列,並且界面操作爲單線程。


2.在javascript中,一般不可以直接操作事件隊列,但是通過 timer api(setTimeout, clearTimeout, setInterval, and clearInterval)事實上我們可以向事件隊列發送低優先級的 timer events (WM_TIMER),即參數指定的時間並不一定能夠精確保證。


3.即使當前事件隊列爲空並且設定了參數timeout爲0,由於存在平臺(操作系統,瀏覽器)相關的 timer resolution即最短 timeout 時間,並不能保證會立即執行 ,在xp sp3下,firefox3平均需要10ms,ie6需要16毫秒,chrome4則只需要4ms,纔會開始執行。

 

postMessage:

 

由於 html5 引入 window.postMessage 事實上給我們除了timer之外的操作事件隊列的方式,可以自定義事件放入事件隊列中,即不存在 timer api的限制 ,在 setTimeout: how to get the shortest delay 即利用了這點,提供了標準兼容瀏覽器下最接近0的timeout

 

Js代碼
  1. ( function  () {  
  2.     var  timeouts = [];  
  3.     var  messageName =  "zero-timeout-message" ;  
  4.     function  setZeroTimeout(fn) {  
  5.         timeouts.push(fn);  
  6.         window.postMessage(messageName, "*" );  
  7.     }  
  8.     function  handleMessage(event) {  
  9.         if  (event.source == window && event.data == messageName) {  
  10.             event.stopPropagation();  
  11.             if  (timeouts.length > 0) {  
  12.                 var  fn = timeouts.shift();  
  13.                 fn();  
  14.             }  
  15.         }  
  16.     }  
  17.     window.addEventListener("message" , handleMessage,  true );  
  18.     window.setZeroTimeout = setZeroTimeout;  
  19. })();  

 

轉自:http://yiminghe.javaeye.com/blog/636369

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章