kuhaku kuhaku - 1 month ago 8
Javascript Question

About javascript runtime behavior and interval

When there's an interval method running the background, can it cause the current function to stop in the middle, go do the interval method and then return to the current function?

For example:

setInterval(bar, 1000);

function foo(){
a();
b();
c();
}

foo();


Is it possible that when reaching
b()
for example to go and do
bar
or
bar
will execute only after the current function (
foo
) is done?

PS: I'm asking about how it will work on Chrome.

Answer

No, it's not possible. The interval is added to the events loop (queue) and new item from this event queue is only picked up when the call stack is empty. This means that the foo should finish executing before new item is processed from the queue. Moreover, it's not only functions added through interval won't get executed until foo is finished, it's all other things like UI events and network request callbacks.

Here is a good talk that explains what this queue is.

Comments