d3.timer是否在重新运行回调之前等待回调完成?

杰里米·泰特鲍姆(Jeremy Teitelbaum)

d3.timer的文档为:

d3.timer(callback [,delay [,time]])<>

安排新的计时器,重复调用指定的回调,直到计时器停止。可以指定一个可选的数字延迟(以毫秒为单位),以在延迟后调用给定的回调。如果未指定delay,则默认为零。延迟是相对于指定时间的毫秒数;如果未指定时间,则默认为现在。

“反复调用指定的回调”是什么意思?更准确地说,d3.timer是否等待回调完成,然后再次运行它?

鲁本·赫斯鲁特(Ruben Helsloot)

这取决于“等待回调完成”的含义。它是一个非常慢的功能,可以同步运行(因此连续运行)吗?好的。

d3.timer(() => {
  const now = Date.now();
  while(Date.now() - now < 1000) {}; // do nothing, but keep the process engaged
  console.log("Ping");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

但是,如果它是一个异步函数(例如API调用),可以对流程进行调度,则不会。

let i = 0,
  j = 0;
d3.timer(() => {
  // Break after 100 iterations
  if(j > 100) {
    return true;
  }

  // do nothing, but release the process
  // so the thread can go do other things
  console.log("Scheduled promise", j);
  j++;
  
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(i);
      console.log("Resolved promise", i);
      i++;
    }, 1000);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章