Skip to content

Instantly share code, notes, and snippets.

@greggman
Created Sep 24, 2021
Embed
What would you like to do?
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