Last active
September 24, 2021 00:43
-
-
Save greggman/6d1741620005ca8c3cf37b1fd1490644 to your computer and use it in GitHub Desktop.
async loop with postMessage based pause
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
/*bug-in-github-api-content-can-not-be-empty*/ |
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
<pre id="count"></pre> |
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
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 = 1000; | |
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`); | |
})(); |
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
{"name":"async loop with postMessage based pause","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