# The Event Loop
# The event loop in a web browser
A simple example of this is in the browser. Consider the following example:
In this example, the host environment is the web browser.
- The HTML parser will first execute the
<script>. It will run to completion.
- The call to
setTimeout(opens new window) tells the browser that, after 100 milliseconds, it should enqueue a task (opens new window) to perform the given action.
- In the meantime, the event loop is then responsible for continually checking if there's something else to do: for example, rendering the web page.
- After 100 milliseconds, if the event loop is not busy for some other reason, it will see the task that
setTimeoutenqueues, and run the function, logging those two statements.
- At any time, if someone clicks on the body, the browser will post a task to the event loop to run the click handler function. The event loop, as it goes around continually checking what to do, will see this, and run that function.
<script>element is invoked immediately
setTimeouttask is posted to the event loop and run once
- The click handler task can be posted many times and run each time
One last thing: what do we mean by saying that each event loop task "runs to completion"? We mean that it is not generally possible to interrupt a block of code that is queued to run as a task, and it is never possible to run code interleaved with another block of code. For example, even if you clicked at the perfect time, you could never get the above code to log
"onclick" in between the two
setTimeout callback log 1/2"s. This is due to the way the task-posting works; it is cooperative and queue-based, instead of preemptive.
# Asynchronous operations and the event loop
and in Node.js we see things like
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".