I’m confused as why one, two and three are printed even after encountering an error.
Here’s the code:
setTimeout(() => {
console.log("one");
}, 1000);
setTimeout(() => {
console.log("two");
}, 2000);
setTimeout(() => {
console.log("three");
}, 3000);
console.log(neha);
I was expecting just an error without printing set timeout values as per my knowledge js engine runs console.log first and then set timeout after their particular timeframe. Correct me if I am wrong and I am new to Stackoverflow too. It’s my first question.
2
Answers
setTimeout
inserts a new message into the queue of the event loop. Each message is processed and if an error occurs, the execution of this concrete message is stopped but the execution (processing) of the messages in the queue goes on.Update:
I just found out that there is already a related question with a lot of great answers here Understanding the Event Loop
When your code runs, it schedules the three setTimeout functions to run after their specified time intervals.
The console.log(neha); line throws an error because neha is not defined. This error is logged to the console.
Despite the error, the setTimeout functions continue to run as they are asynchronous and independent of the error in the previous line.
After 1 second, "one" is logged to the console.
After 2 seconds, "two" is logged to the console.
After 3 seconds, "three" is logged to the console.
So, even though there’s an error in your code, the setTimeout functions will still execute and log their messages according to their respective time intervals.
The error does not halt the execution of these asynchronous operations.