Reputation: 461
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.
Upvotes: 1
Views: 1374
Reputation: 51
Each call you make it running in it's own background thread (it's own unique operation), when you call setTimeout, you're telling JavaScript that you want to execute your code after 1 second has passed.
If you wanted to make this last 5 seconds you would do something along the lines of:
setTimeout(function() {
console.log("First task")
setTimeout(function() {
console.log("Second task");
},1000);
},1000);
This would execute the first task, once called it will execute the second task
Edit: I saw another post about doing it non-async, you want to avoid doing anything non-async in JavaScript as it will hold up the browser which is general is a bad practice and bad user experience
Upvotes: 1
Reputation: 1250
From the MDN page:
The setTimeout() method ... sets a timer which executes a function or specified piece of code once the timer expires.
Upvotes: 0
Reputation: 2049
because setTimeout works asynchronously, means all of these 5 statements will be executed simultaneously and all of these will start waiting for 1 second. and after one second all will be executed. hope it clears.
Upvotes: 3