If you’re talking about Asynchronous JavaScript, it’s really important to understand the event loop and how things work under the hood.
Let’s take an example to understand a simple asynchronous operation in JavaScript.
setTimeout(() => {
console.log("Hello")
}, 1000)
console.log("Me first")
//me first
//Hello
setTimeout
is a browser API that executes a piece of code after a specified time interval like 1000ms, 2000ms, etc. You can read about it in detail here.
The order of execution will be me first and then Hello- because of the non-blocking nature of JavaScript.
We all know that JavaScript works on as single thread, also known as the main thread. In case of async scenarios like waiting for some seconds to complete a task, the main thread needs to be blocked— but that’s not really how JavaScript works. Let’s dig into it!
setTimeout
is called, a timer fires up in the browser. In our case, the timer expires in 1000ms. This timer has a reference to our callback function. In order for the cb function to be executed, it needs to be pushed to the call stack. CallStack is a data structure that keeps track of functions and the order in which they are executed.Coming back to our example again, JavaScript encounters the first line; Oh! It’s a setTimeout
, we’ll have to wait for it to finish in the background. Meanwhile, jump to the next line which reads console.log("Me first")
. So it just logs that out. After, it logs “Hello”.
Similarly, if we take this example, the result will still be the same!!
function sayHello() {
console.log("Hello")
}
function meFirst() {
console.log("me first")
}
setTimeout(sayHello, 1000)
meFirst()
//me first
//hello
setTimeout
is invoked; it goes to the Web API land where the timer runs.meFirst
function is pushed to the stack, prints ”me first”, and gets popped off.sayHello
gets queued to the callback queue/task queue.meFirst
has already been popped off.sayHello
to the stack.If you want to visualize, you can check out for yourself how the event loop is working- here.
Thank You for reading this article. Follow me on Twitter for more updates.