0

As per MDN, the callbacks in setTimeout() function are executed only when the stack on the main thread is empty.Is this same for setInterval() function? If yes then when both these function are present then which will be executed first?

I am using node.js environment I am getting some inconsistent result with below code

var i = 0;
function cal(){
     i++; 
console.log(i);
if(i == 2) clearInterval(inter);
}
const inter = setInterval(cal,2000);

setTimeout(()=> {
    console.log('Hello');
},2000)

the output I am getting is

1
Hello
2

but If I run below code

setTimeout(()=> {
    console.log('Hello');
},2000)

var i = 0;
function cal(){
     i++; 
console.log(i);
if(i == 2) clearInterval(inter);
}

const inter = setInterval(cal,2000);

the output I am getting is

Hello
1
2
  • 1
    What's the problem? You start the interval before the timeout in the first case, so the interval logs first. You start the timeout before the interval in the second case, so the interval logs second... You would have to start the interval and timeout at exactly the same nanosecond in order to determine "which came first". – Heretic Monkey Nov 03 '20 at 16:05
  • In first case it should log 1 2 hello . the entire setInterval must be be executed before starting timeout – sagar caset Nov 03 '20 at 16:11
  • That's not how `setInterval` works. – Heretic Monkey Nov 03 '20 at 16:12
  • @sagarcaset "_the entire setInterval must be be executed before starting timeout_" - What do you mean by _"entire setInterval"_? Each call to `cal` will log `i` only once. – Yousaf Nov 03 '20 at 16:12
  • @HereticMonkey as per MDN main thread should be free for callback in setTimeout() to be executed – sagar caset Nov 03 '20 at 16:17
  • @sagarcaset the main thread is free between the two executions of your interval, at which point the timeout runs – Darkhogg Nov 03 '20 at 16:27
  • `setInterval` schedules actions to be taken at certain times. It does not block the thread during the interval, so `setTimeout` is free to run and prints "Hello". Approximately 2000ms later, `setInterval` runs the second scheduled function call, prints `2`, and clears the interval. I suggest reading that article I posted. The answers go into much more detail than I can in a comment. – Heretic Monkey Nov 03 '20 at 16:30

0 Answers0