I was expecting the output to be 3->2->1
but instead my output is 1->3->2
Why I am getting differently?
JavaScript
x
11
11
1
setTimeout(() => {
2
console.log(`1 work is done`);
3
4
setTimeout(() => {
5
console.log(`2 work is done`);
6
}, 3000);
7
8
setTimeout(() => {
9
console.log(`3 work is done`);
10
}, 1000);
11
}, 5000);
Advertisement
Answer
The setTimeout()
timings are not correct. Your parent setTimeout()
method it’s set to execute after 5000 ms
, then it enters the function and the first one it triggers is the one without Timeout which is your first console.log()
, after that it executes the second one which is the third console.log()
and finally the console.log()
in the middle.
In summary, you forgot to setTimeout()
to the first console.log()
. If you want that one to be the last, it should have a Timeout bigger than the second and third. Try the following snippet:
JavaScript
1
7
1
setTimeout(() => {
2
3
setTimeout(() => { console.log("1 work is done") }, 2000);
4
setTimeout(() => { console.log("2 work is done") }, 1000);
5
console.log("3 work is done")
6
7
}, 1000);