class AI {
constructor() {
this.tasks = [];
this.sTimer = null;
}
async start() {
for (let i = 0; i < this.tasks.length; i++) {
const current = this.tasks[i];
const next = this.tasks[i + 1];
if (next && next.type === "cancel") {
i += 1;
console.log("cancel success");
continue;
}
if (current.type === "cancel") {
console.log("notask");
continue;
}
if (current.type === "talk") {
console.log("talk");
continue;
}
if (current.type === "sleep") {
console.log("sleeping...");
await this.sleepHelper(current.payload * 1000);
}
}
clearTimeout(this.sTimer);
}
tryStart() {
if (this.sTimer) {
clearTimeout(this.sTimer);
}
this.sTimer = setTimeout(() => {
this.start();
}, 0);
}
sleepHelper(timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, timeout);
});
}
talk() {
this.tasks.push({
type: "talk"
});
this.tryStart();
return this;
}
sleep(s) {
this.tasks.push({
type: "sleep",
payload: s
});
this.tryStart();
return this;
}
cancel() {
this.tasks.push({
type: "cancel"
});
this.tryStart();
return this;
}
}
new AI()
.cancel()
.talk()
.sleep(3)
.talk()
.cancel()
.sleep(3)
.sleep(3)
.cancel()
.talk()
.cancel()
.talk();