DEV Community

Hihi
Hihi

Posted on • Updated on

Javascript event loop - approach the first meet

Let's take a context in a browser where we can execute JS directly in the console. Browsers provide JS runtime engine so that we can run the code in the console. Beside the JS engine, browsers also have alot of other built-in tools like HTML parsers, networking, storages,... And the Web API is one of the pieces in the browsers tools.
To this point we can note that JS runtime and Web API is 2 separately tools in the browser. This is important to acknowledge before we continued to the Event loop.

Image description
Now consider this snippet:

console.log('start')

setTimeout(() => {
    console.log('Time is up!')
}, 0);

console.log('end')
Enter fullscreen mode Exit fullscreen mode

When we execute the snippet, the log now shows:

start
end
Time is up!
Enter fullscreen mode Exit fullscreen mode

Why shouldn't the log be this order start - time is up! - end although we set the timer to 0 in setTimeout?

Debug the event loop

Firstly, keep in mind that JS doesn't provide the setTimeout function. It's part of the Web API that provided by browser. So it has nothing to do with the Javascript things.

Image description

When the code run, the functions are gradually added to the Callstack and then executed immediately.
While the console.log() functions are freshly executed right away and log the texts, the setTimeout is a special function from Web API. When it's called, the Web API will get the hands in: it holds the callback passed in setTimeout for a t second.

Image description

After t second, the callback is pushed to the callback queue, waiting in it to be executed:

Image description

The Event loop is constantly checking the callstack: if the callstack is empty, the callback queue will dequeue it, bringing the instance waiting in the queue to the callstack and then execute it

Image description

And finally, the console.log('Time is up!') is executed.

Image description

Conclusion

  • From the snippet above, we can see that if we use the special functions (setTimeout, setTimeInterval) from the Web API kit, the comprised instances (callbacks) in these function must go to the Web API, then go to the waiting queue from the callback queue, waiting for the callstack to be empty and then dequeue to the callstack for execution.
  • In the meanwhile, the JS native functions (console) will take place in the callstack, no waiting for the setTimeout. This is called Asynchronous/Non-blocking

Top comments (0)