Asynchronous operations and the event loop
suggest changeMany interesting operations in common JavaScript programming environments are asynchronous. For example, in the browser we see things like
window.setTimeout(() => {
console.log("this happens later");
}, 100);
and in Node.js we see things like
fs.readFile("file.txt", (err, data) => {
console.log(data);
});
How does this fit with the event loop?
When these statements execute, they ask the host environment (the browser or the Node.js runtime) to do something, often outside this turn of the event loop. When that work finishes (here, waiting 100 milliseconds or reading file.txt), the host posts a task that calls the callback with the result. fs must be loaded with require("node:fs") or import fs from "node:fs" before readFile is used.
The event loop is then busy doing its thing: rendering the webpage, listening for user input, and continually looking for posted tasks. When it sees these posted tasks to call the callbacks, it will call back into JavaScript. That’s how you get asynchronous behavior!