Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Stack while using setTimeout()

Tags:

javascript

I am a bit confused about setTimeout.I want to confirm whether the output for the following code will always be:

inside abc
inside sample

The code:

function abc() {
    xyz();

    // interactions and modifications in DOM 
    $("#id1").append("something");
    $("#id2").val("set something");
    $("#id3").after("create some dynamic element");
    // 10 to 20 interaction more...

    console.log('inside abc');
}

function xyz() {
    setTimeout(function() {
        sample();
    },0);  
}

function sample() {
    console.log('inside sample')
}

It would be great,if somebody could explain the whole flow with the call stack.

like image 534
Shekhar Joshi Avatar asked May 11 '26 06:05

Shekhar Joshi


2 Answers

Yes, it will always have that output.

The callback inside a setTimeout will not be called until the execution context is clear - i.e. the currently executing sequence of code has finished.

This means that even if you do

setTimeout(function () { console.log("1 second!"); }, 1000);

var start = +new Date();
while ((+new Date()) - start < 5000) {}

1 second! will not be logged any sooner than 5 seconds have passed.

like image 194
JLRishe Avatar answered May 13 '26 19:05

JLRishe


setTimeout() will run asynchronously after finishing current execution block. So output should be same always:

inside abc
inside sample

Javascript internally manage an event queues internally for all async tasks. Every time it checks its async queue after finishing current execution block.

like image 41
Samir Das Avatar answered May 13 '26 21:05

Samir Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!