Skip to content

Instantly share code, notes, and snippets.

@hliyan
Created July 29, 2019 11:57
Show Gist options
  • Save hliyan/6cc2b6d1bf060e59dbca6e34083ad324 to your computer and use it in GitHub Desktop.
Save hliyan/6cc2b6d1bf060e59dbca6e34083ad324 to your computer and use it in GitHub Desktop.
Events using postMessage
<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