2 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
我認(rèn)為setTimeout在這種情況下這將是一個(gè)更好的選擇:
async function update() {
const t1 = new Date();
await wait_for_response();
setTimeout(update, Math.max(0, 1000 - new Date + t1));
}
update();

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
這個(gè)使用承諾鏈的簡(jiǎn)單構(gòu)造可以為您處理:
let lastPromise = Promise.resolve();
function update() {
lastPromise = lastPromise.then(wait_for_response, wait_for_response);
}
setInterval(update, 1000);
如果我們擔(dān)心鏈無(wú)限增長(zhǎng),我們可以使用這個(gè)版本:
let lastPromise = Promise.resolve();
function update() {
const p = lastPromise;
function cleanup() {
if (lastPromise === p) {
lastPromise = Promise.resolve();
}
}
lastPromise = lastPromise
.then(wait_for_response, wait_for_response)
.then(cleanup, cleanup);
}
setInterval(update, 1000);
添加回答
舉報(bào)