Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetTimeout And SetImmediate with console.log

Can anyone please explain why i am getting this below two types of output for adding and removing console.log between setTimeout and setImmediate.

Why I am getting different output while executing example 1 and Why I am getting same output for example 2. Please tell me difference between setTimeout and setImmediate

Example 1:

setTimeout(function(){
        console.log("inside timeout")
});

setImmediate(function(){
        console.log("inside immediate")
});

Output:

inside immediate
inside timeout

Example 2:

console.log(1)

setTimeout(function(){
        console.log("inside timeout")
});
console.log(2)
setImmediate(function(){
        console.log("inside immediate")
});
console.log(3)

Output:

1
2
3
inside timeout
inside immediate
like image 783
Deepak Avatar asked Jul 28 '26 11:07

Deepak


1 Answers

Let's talk about the situation in nodeJs. Actually the order of the below code is can not be guarantee.

 setTimeout(function(){
            console.log("inside timeout")
    });

    setImmediate(function(){
            console.log("inside immediate")
    });

If you run it many times, you will found that, in high probability it is

inside immediate
inside timeout, 

but sometimes it's in reverse. You second demo is same.

In nodeJs there one thing call event loop, For the asynchronous function, the event loop forward it to libuv and then it be forward to the OS. For eg. When the time in setTimeout is coming, the callback function be set into a queue, it will be invoked after the synchronous thread is done. For different asynchronous task there are four different queue, the setTimeout's queue is run before the setImmediate's queue.But the setTimeout's cut down return depend on the CPU's time slice, even the setTimeout(0), so it is not stable.

like image 115
sinbar Avatar answered Jul 30 '26 23:07

sinbar



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!