🔰event loop
JS ⟩ async code ⟩ event loop
replit ⟩ event loop
const { log } = console;
// ----------
// case 1
// ----------
try {
setTimeout(() => {
throw new Error("Woosh"); // ⭐ async code
}, 2000);
} catch (_) {
log("Caught!"); // this will not run❗
}
// ----------
// case 2
// ----------
Promise.resolve("Done").then(console.log); // ⭐ async code
console.log("Me first!");
// ----------
// case 3
// ----------
let start = Date.now();
const elapsed = () => Date.now() - start;
// 1. send a minitask to event loop (plan to run in 20 ms)
setTimeout(() => {
log("Timeout ran at:", elapsed()); // ⭐ async code
}, 20);
// 2. fiddle around for (at least) 50 ms
while (elapsed() < 50) { }
// 3. sync code ends
log("Wasted time until:", elapsed());
// (sync code ends)
// -----------------------
// Me first!
// Wasted time until: 67
// ⭐ (async code begins)
// -----------------------
// Done
// Timeout ran at: 72
// Error: Woosh
Eloquent JS ⟩ Asynchronous Programming ⟩ The Event Loop
Last updated