js实现真正0ms的setTimeout

最新更新时间:2020年08月12日22:30:16

《猛戳-查看我的博客地图-总有你意想不到的惊喜》

本文内容:定时器window.setTimeout

概述

在浏览器中,setTimeout()/setInterval() 的每调用一次定时器的最小间隔是4ms,这通常是由于函数嵌套导致(嵌套层级达到一定深度),或者是由于已经执行的setInterval的回调函数阻塞导致的。

实现源码

// Only add setZeroTimeout to the window object, and hide everything else in a closure.
(function() {
     
    var timeouts = [];
    var messageName = "zero-timeout-message";

    // Like setTimeout, but only takes a function argument.  There's
    // no time argument (always zero) and no arguments (you have to
    // use a closure).
    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);

    // Add the one thing we want added to the window object.
    window.setZeroTimeout = setZeroTimeout;
})();

实例

console.log(1);
setTimeout(()=>{
     console.log(2)},0)
setZeroTimeout(()=>{
     console.log(3);})
new Promise((resolve)=>{
     resolve(4)}).then((res)=>{
     console.log(res)})
console.log(5);
// 1
// 4
// 4
// 3
// 2

伪方案

微任务模式

console.log(1);
new Promise((resolve)=>{
     resolve()}).then(()=>{
     console.log(2)})
console.log(3);
// 1
// 3
// 2

扩展知识 postMessage

设计模式:发布-订阅模式(观察者模式)

function handleMessage(event) {
     
	console.log(event)
	//event.data {name: "wanshaobo", age: 18}
}
window.addEventListener("message", handleMessage, true);
window.postMessage({
     name:'wanshaobo',age:18}, "*");

参考资料

  • window.postMessage
  • setTimeout with a shorter delay
  • window.setTimeout

感谢阅读,欢迎评论^-^

打赏我吧^-^

你可能感兴趣的:(JavaScript)