Event loop
Under the hood, JavaScript manages concurrency and asynchrony. JavaScript is a language with only one thread. In this usage, a thread refers to an execution path. Tasks will have to wait for one another if there is only one path, and only one item can happen at once.
The event loop is this single executor. It is a method for carrying out the actual work. Given that you recently learnt about concurrency and performing tasks simultaneously yet asynchronously, you might be curious about this. JavaScript is single-threaded, but that doesn't mean it can't dispatch some tasks and wait for them to return. This is exactly how JavaScript performs tasks in a multithreaded manner.
Call stack and callback queue
All the tasks that JavaScript needs to perform are queued up on a call stack, which is how it operates. The event loop is a process that continuously monitors this call stack. When tasks need to be completed, the event loop completes them one at a time. The tasks at the top are completed first.
Here's a tiny script:
Here's a visualization of the call stack and event loop for this script.
No multithreading is going on here. But it is here:
The web API of the browser receives the setTimeout() task. When finished, this shows up in a specific location called the callback queue. The event loop will scan the callback queue for available tasks only when the call stack is empty (and only then!). Callbacks that are still awaiting action will be carried out one by one. The event loop first checks the call stack for work after each action.
Here's a visualization of the situation with the outsourcing of
setTimeout() :
When setTimeout() expires, the event loop will have done whatever was on the call stack already, and will check the callback queue and execute any tasks on there:
And this is what it will output:
Let's see if you read the above text well.
What do you think will happen when we set the timer to 0 , like here?
The output from this will be the same. When the timer reaches 0 it will also outsource the call to setTimeout(). The event loop won't even check the callback queue until the callstack is empty, despite the fact that the callback is immediately added to the callback queue. So even if the timer is at So even if the timer is at 0,
it will still print:
- Sorry I'm late even
- 9 o'clock
About Anas Aqeel
I’m currently working Frontend Development having an experience of building Web applications with JavaScript / React-JS / Node-JS and some other cool libraries and frameworks. I’m currently learning web3 technologies such as Solidity, Ether-JS and web3.