JavaScript Asynchronous operations and the event loop


Example

Many 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?

How this works is that when these statements execute, they tell the host environment (i.e., the browser or Node.js runtime, respectively) to go off and do something, probably in another thread. When the host environment is done doing that thing (respectively, waiting 100 milliseconds or reading the file file.txt) it will post a task to the event loop, saying "call the callback I was given earlier with these arguments".

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!