JavaScript Interview Practical Question: Guess the Output of the below code.
console.log("India");
const mmt = setTimeout(() => { console.log("Kuchaman"); }, 0);
console.log("Rajasthan");
console.log("India");
const mmt = setTimeout(() => { console.log("Kuchaman"); }, 0);
console.log("Rajasthan");
Breaking It Down
Let’s analyze what each line does:
- First
console.log()statement:
javascriptCopyconsole.log("India");
This will immediately log"India"to the console. - The
setTimeout()function:
javascriptCopyconst mmt = setTimeout(() => { console.log("Kuchaman"); }, 0);Here, we schedule the message"Kuchaman"to be logged withsetTimeout(). The delay is set to0milliseconds, meaning we’re asking JavaScript to execute the callback function (which logs"Kuchaman") as soon as possible, but not immediately.You might expect the message to appear right after"India", but JavaScript doesn’t execute this immediately. Why? Let’s explore how JavaScript handles asynchronous code. - Second
console.log()statement:javascriptCopyconsole.log("Rajasthan");This line will also execute immediately after the firstconsole.log()because there’s no delay in it.
The JavaScript Event Loop
JavaScript is single-threaded, which means it can only execute one operation at a time. But it can handle asynchronous tasks like timers, network requests, and user events without blocking the execution of other code. This is achieved using something called the event loop.
When we invoke setTimeout(), even with a delay of 0 milliseconds, the callback function does not run immediately. Instead, it gets placed in the task queue (or message queue) after the current code execution finishes. The event loop will only pick up the tasks from the queue once the current stack of synchronous code is done executing.
In this case, after "India" and "Rajasthan" are logged, the event loop picks up the setTimeout() callback (the function that logs "Kuchaman").
What Happens in Our Code?
When the script runs, here’s the order of events:
"India"is logged synchronously.setTimeout()is called, but the callback is pushed to the task queue."Rajasthan"is logged synchronously.- The event loop now checks the task queue and sees the callback for
"Kuchaman". It executes the callback and logs"Kuchaman".
The Output:
India
Rajasthan
Kuchaman
Why Does setTimeout(0) Not Run Immediately?
At first glance, it may seem like setTimeout(0) should run immediately, since the delay is set to zero. However, the event loop handles this slightly differently. Even with a zero-delay, JavaScript doesn’t execute the callback function right away. It still has to wait for the currently executing code (like "India" and "Rajasthan") to complete first. Only then will it run the callback in the task queue.
Practical Use of setTimeout()
So why would you use setTimeout() with a delay of 0 milliseconds? It can be a handy way to defer the execution of code until the current execution context is complete. For example:
- Allowing the UI to update before performing further operations.
- Breaking up heavy computations so the browser remains responsive.
- Scheduling operations that shouldn’t interrupt the current execution flow but still need to be done soon.
Conclusion
In summary, while setTimeout(0) doesn’t mean immediate execution, it ensures that the callback function is placed in the task queue and executed as soon as the JavaScript runtime has finished processing the current stack of operations. Understanding how this works is crucial for mastering JavaScript’s asynchronous behavior and writing more efficient, non-blocking code.
Next time you use setTimeout(), keep in mind how the event loop processes your asynchronous tasks. It’s one of the essential aspects of working with JavaScript and handling asynchronous events!
