1 回答

TA貢獻1831條經驗 獲得超9個贊
這取決于你所說的“等待回調完成”的意思。它是同步運行(因此連續運行)的非常慢的函數嗎?好的。
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>
添加回答
舉報