0

I have a simple question about setTimeout function

My function:

function myFunc(){
   // some code here
}

What's different when

I call a function with and without setTimeout:

myFunc();
setTimeout(function(){
   myFunc();
}, 0);

Can someone explain help me? Thank you.

Ryan Nghiem
  • 2,417
  • 2
  • 18
  • 28
  • if you call it with `setTimeout` the browser will finish any current tasks first, and then run your function (asynchronously) – Alnitak Jul 08 '19 at 10:56
  • With `setTimeout` it will be executed *sometime later* (very soon), so other things may happen in the meantime… – deceze Jul 08 '19 at 10:56

2 Answers2

1

setTimeout waits for a given delay then schedules a new task for its callback. This is why setTimeout is logged after script end, as logging script end is part of the first task, and setTimeout is logged in a separate task. Right, we're almost through this, but I need you to stay strong for this next bit…

Tasks are scheduled so the browser can get from its internals into JavaScript/DOM land and ensures these actions happen sequentially. Between tasks, the browser may render updates. Getting from a mouse click to an event callback requires scheduling a task, as does parsing HTML, and in the above example, setTimeout.

https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

Vadim Hulevich
  • 1,803
  • 8
  • 17
0

setTimeout(,0) will call after all current queue will be finished, and normal function call goes in the queue first.

You can see here:

function myFunc1(){
   console.log("In myFunc1");
}

function myFunc2(){
   console.log("In myFunc2");
}

setTimeout(function(){
   myFunc1();
}, 0);

myFunc2();
Paresh Barad
  • 1,544
  • 11
  • 18