I came across this simple(or what I thought so) question on a Javascript MCQ Test:
After how much time will the following code execute entirely?
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
Options
A) 1 second
B) 2 seconds
C) 4 seconds
D) 5 seconds
I answered as option D) 5 seconds since EACH line above will take 1000 milliseconds to execute i.e a total of 5000 milliseconds = 5 seconds
But in the results, it said that the actual answer is Option A) 1 second.
I executed those five lines in my console (altogether) and the entire code executed after 1 second like the answer said.
I don't understand the logic behind the right answer, and why my reasoning was wrong.
console.log("hi")is not wrapped in afunction, so it will execute immediately. You also have an extra), so this is likely not the actual code.setTimeout( function(){console.log("hi")}, 1000 );. setTimeOut is wrong, we need a function around the console.log and also a last parenthesis should be removed! Then the answer is as its said, due to async behaviour of setTimeout, as it will return instantly and run the callback at specified time.). They were written by mistake. @Kobi