2 回答

TA貢獻1801條經驗 獲得超8個贊
您安排兩個回調:
wait(500, function(x) {return x + 5}) // execute after 500ms
wait(250, function(x) {return x * 2}) // execute after 250ms
第一個參數是回調將運行的時間。由于第二個wait調用具有較低的第一個參數,因此它首先運行。
在 250 毫秒左右,從result10 開始,x * 2乘以result2,得到 20。
然后,在 500 毫秒左右,x + 5運行,讓你達到 25。
如果您希望能夠執行此類操作以使代碼看起來更按順序運行,請使用 Promisesawait代替:
let result = 10;
function wait(time,f) {
return new Promise(resolve => setTimeout(() => {
result = f(result);
resolve();
}, time));
}
(async () => {
await wait(250, x => x * 2);
await wait(250, x => x + 5);
console.log(result);
})();

TA貢獻1853條經驗 獲得超18個贊
如果您希望在 Edge 15 以下,這是一種向后兼容的方式來實現您想要的:
const delay = (()=>{
let n = 0;
return (time, func)=>{
n += time; setTimeout(func, n);
return delay;
}
})();
let x = 10;
delay(500, ()=>{
x += 5;
console.log(x);
})(250, ()=>{
x *= 2;
console.log(x);
});
添加回答
舉報