1 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
這取決于你所說(shuō)的“等待回調(diào)完成”的意思。它是同步運(yùn)行(因此連續(xù)運(yùn)行)的非常慢的函數(shù)嗎?好的。
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>
但如果它是一個(gè)異步函數(shù)——比如一個(gè) API 調(diào)用——它會(huì)取消進(jìn)程的調(diào)度,那么就不會(huì)。
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>
添加回答
舉報(bào)