James
James

Reputation: 127

Settimeout not returning instantly

I was practicing with callback functions and this question is one I can't seem to figure out.

function foo () {    
  var data = 10;    
  bar(function (players) {
    data = players;
  });    
  return data;
}

function bar (callback) {
  setTimeout(callback, 0);
}

var result = foo();

I expected result to be undefined since data = players and there is nothing passed in as players. Since the setTimeout function uses 0 as the delay, shouldn't it run first, and then return data? I looked at the MDN page and there seems to be information on throttling for nested timeouts to >=4ms. Does this also apply in this case?

Upvotes: 0

Views: 51

Answers (1)

Felix Kling
Felix Kling

Reputation: 816364

Since the setTimeout function uses 0 as the delay, shouldn't it run first, and then return data?

No, even with a delay of 0, the callback passed to setTimeout is scheduled to run in the next tick of the event loop.

In other words, the callback is guaranteed to be executed after the current execution ran to completion.

Upvotes: 1

Related Questions