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);
});
添加回答
举报
