Created
July 29, 2019 11:57
-
-
Save hliyan/6cc2b6d1bf060e59dbca6e34083ad324 to your computer and use it in GitHub Desktop.
Events using postMessage
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
<html> | |
<body> | |
<div> | |
<button onClick="onButton()">Hello</button> | |
</div> | |
<script> | |
// credit: https://dbaron.org/log/20100309-faster-timeouts | |
const eventQueue = []; | |
const postEvent = (fn) => { | |
if (typeof fn != "function") { | |
throw Error("postEvent: not a string"); | |
} | |
eventQueue.push(fn); | |
window.postMessage("custom-event", "*"); | |
}; | |
const onEvent = (event) => { | |
if (event.source != window || event.data != "custom-event") | |
return; | |
event.stopPropagation(); | |
if (eventQueue.length == 0) | |
return; | |
const fn = eventQueue.shift(); | |
fn(); | |
}; | |
window.addEventListener("message", onEvent, true); | |
const onButton = () => { | |
//for (let i = 0; i < 100; i++) { // if you want to check perf | |
postEvent(() => { | |
console.log("hello" + i); | |
}); | |
//} | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment