Interview icon indicating copy to clipboard operation
Interview copied to clipboard

Day376:setTimeout为什么最小只能设置4ms,怎么实现一个0ms的setTimeout?

Open qappleh opened this issue 4 years ago • 1 comments

qappleh avatar Aug 02 '21 02:08 qappleh

抄一下大佬的0ms延迟

    // 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;
    })();

原文地址:https://dbaron.org/log/20100309-faster-timeouts

EickeOe avatar Aug 03 '21 04:08 EickeOe