Skip to content

Instantly share code, notes, and snippets.

@luciopaiva
Created June 10, 2018 00:02
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 luciopaiva/7b8577208a036d02d984e80a1d6e2e21 to your computer and use it in GitHub Desktop.
Save luciopaiva/7b8577208a036d02d984e80a1d6e2e21 to your computer and use it in GitHub Desktop.
Async Javascript experiments
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