Skip to content

Instantly share code, notes, and snippets.

@greggman
Created September 24, 2021 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/fcf4ef5d21ed702aa7e27f8e3e7b5e86 to your computer and use it in GitHub Desktop.
Save greggman/fcf4ef5d21ed702aa7e27f8e3e7b5e86 to your computer and use it in GitHub Desktop.
async loop with postMessage based pause (long)
/*bug-in-github-api-content-can-not-be-empty*/
<pre id="count"></pre>
const pause = (function() {
let reqId = 0;
const reqs = new Map();
window.addEventListener('message', (e) => {
const resolve = reqs.get(e.data);
if (resolve) {
reqs.delete(e.data);
resolve();
}
});
return _ => new Promise(resolve => {
const id = reqId++;
reqs.set(id, resolve);
window.postMessage(id);
});
})();
(async function() {
const countElem = document.querySelector('#count');
const start = performance.now();
const limit = 10000000;
for (let i = 0; i < limit; ++i) {
countElem.textContent = `${i + 1} / ${limit}`;
await pause();
}
const end = performance.now();
console.log(`elapsed time: ${((end - start) / 1000).toFixed(2)} seconds`);
})();
{"name":"async loop with postMessage based pause (long)","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment