简体   繁体   English

Settimeout不会立即返回

[英]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. 我期望结果是不确定的,因为data = players并且没有任何内容作为播放器传递。 Since the setTimeout function uses 0 as the delay, shouldn't it run first, and then return data? 因为setTimeout函数使用0作为延迟,所以它不应该先运行然后返回数据吗? I looked at the MDN page and there seems to be information on throttling for nested timeouts to >=4ms . 我看了看MDN页面,似乎有关于节制嵌套超时>=4ms Does this also apply in this case? 这是否也适用于这种情况?

Since the setTimeout function uses 0 as the delay, shouldn't it run first, and then return data? 因为setTimeout函数使用0作为延迟,所以它不应该先运行然后返回数据吗?

No, even with a delay of 0 , the callback passed to setTimeout is scheduled to run in the next tick of the event loop . 不,即使延迟为0 ,传递给setTimeout的回调也计划在事件循环下一个计时周期运行。

In other words, the callback is guaranteed to be executed after the current execution ran to completion. 换句话说,保证在当前执行完成后才执行回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM