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

d3.timer 的文档如下:

d3.timer(回调[, 延迟[, 时间]]) <>

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

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


哆啦的时光机
浏览 73回答 1
1回答

天涯尽头无女友

这取决于你所说的“等待回调完成”的意思。它是同步运行(因此连续运行)的非常慢的函数吗?好的。d3.timer(() => {&nbsp; const now = Date.now();&nbsp; while(Date.now() - now < 1000) {}; // do nothing, but keep the process engaged&nbsp; console.log("Ping");});<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>但如果它是一个异步函数——比如一个 API 调用——它会取消进程的调度,那么就不会。let i = 0,&nbsp; j = 0;d3.timer(() => {&nbsp; // Break after 100 iterations&nbsp; if(j > 100) {&nbsp; &nbsp; return true;&nbsp; }&nbsp; // do nothing, but release the process&nbsp; // so the thread can go do other things&nbsp; console.log("Scheduled promise", j);&nbsp; j++;&nbsp;&nbsp;&nbsp; return new Promise((resolve) => {&nbsp; &nbsp; setTimeout(() => {&nbsp; &nbsp; &nbsp; resolve(i);&nbsp; &nbsp; &nbsp; console.log("Resolved promise", i);&nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; }, 1000);&nbsp; });});<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript