链式延时调用
export class AwaitTimeout {
constructor() {
// 任务池
this.tasks = [];
this.tasks.push(() => {
this.then();
});
}
// 执行
running() {
setTimeout(() => {
this.then();
});
return this
}
sleep(duration, fn) {
this.tasks.push(() => {
setTimeout(() => {
fn();
this.then();
}, duration);
});
return this;
}
then() {
let task = this.tasks.shift();
task && task();
return this;
}
}
使用:
// 引入
import { AwaitTimeout } from "../../utils/swiper";
const setAwaitTimeout = new AwaitTimeout();
// 使用
setAwaitTimeout
.running()
.sleep(1000, () => {
console.log("过了1秒");
})
.sleep(1000, () => {
console.log("过了2秒");
})
.sleep(1000, () => {
console.log("过了3秒");
})
.sleep(1000, () => {
console.log("过了4秒");
});
评论