关于 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 :
?
(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;
})();
?
?
?
?
?
?