Created
June 10, 2018 00:02
-
-
Save luciopaiva/7b8577208a036d02d984e80a1d6e2e21 to your computer and use it in GitHub Desktop.
Async Javascript experiments
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
function sleep(ms) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
/** | |
* Shows how a timer fails to execute when we block the main thread. See `setIntervalDoesNotWorkWithBlockingWait()` for | |
* a solution to this. | |
* @returns {void} | |
*/ | |
function setIntervalDoesNotWorkWithBlockingWait() { | |
setInterval(() => console.info("hello"), 1000); | |
const end = Date.now() + 3000; | |
console.info("Going to sleep"); | |
while (Date.now() < end) { | |
// hello won't be printed while this loop is busy-waiting! | |
} | |
console.info("Back from sleep"); | |
} | |
/** | |
* Shows how a timer can still work even though we are sleeping, given that we `await` rather than block. | |
* @returns {void} | |
*/ | |
async function setIntervalWorksWithAsynchronousWait() { | |
setInterval(() => console.info("hello"), 1000); | |
console.info("Going to sleep"); | |
await sleep(3000); | |
console.info("Back from sleep"); | |
} | |
/** | |
* What happens when you call `setImmediate()` with `await`. It pushes everything below it to execute in the end of the | |
* current event loop iteration. | |
* @returns {void} | |
*/ | |
async function immediateWithPromises() { | |
console.info("1"); | |
// setImmediate will push 2 to appear after 3 | |
setImmediate(() => { console.info("2"); }); | |
console.info("3"); | |
// awaiting on setImmediate will make 5 be postponed as well, so 4 will end up showing before 5 | |
await new Promise(resolve => setImmediate(() => { console.info("4"); resolve(); })); | |
console.info("5"); | |
} | |
setIntervalDoesNotWorkWithBlockingWait(); | |
setIntervalWorksWithAsynchronousWait(); | |
// immediateWithPromises(); // <-- only works with Node.js because of `setImmediate()` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment