Created
May 4, 2019 18:59
-
-
Save EminQasimov/149ddbd011f7d8202d241d8e17b67537 to your computer and use it in GitHub Desktop.
setTimeout in most browsers doesn't allow a delay less than about 10 milliseconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment