關於 setTimeout 相關的文章:
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 :
- ( function () {
- var timeouts = [];
- var messageName = "zero-timeout-message" ;
- function setZeroTimeout(fn) {
- timeouts.push(fn);
- window.postMessage(messageName, "*" );
- }
- function handleMessage(event) {
- if (event.source == window && event.data == messageName) {
- event.stopPropagation();
- if (timeouts.length > 0) {
- var fn = timeouts.shift();
- fn();
- }
- }
- }
- window.addEventListener("message" , handleMessage, true );
- window.setZeroTimeout = setZeroTimeout;
- })();
轉自:http://yiminghe.javaeye.com/blog/636369