class AI {
constructor () {
this.queue = []
this.timer = null
this.interval = null
this.run()
}
run () {
this.interval = setInterval(() => {
if (this.queue.length > 0 && this.timer === null) {
let [beforeTask, afterTask, time] = this.queue.shift()
beforeTask()
this.timer = setTimeout(() => {
afterTask()
this.timer = null
}, time)
}
})
}
task () {
const beforeTask = () => {}
const afterTask = () => console.log('task')
const time = 0
this.queue.push([beforeTask, afterTask, time])
return this
}
cancel () {
if (this.queue.length === 0) {
console.log('notask')
} else {
let [,afterTask] = this.queue.pop()
if (afterTask.name === 'afterTask' && this.queue.length === 0) {
console.log('cancel')
}
}
return this
}
sleep (num) {
const sleepBeforeTask = () => console.log('等待' + num + '秒')
const sleepAfterTask = () => {}
const time = num * 1000
this.queue.push([sleepBeforeTask, sleepAfterTask, time])
return this
}
}
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();
13 回答13k 阅读
7 回答2.2k 阅读
3 回答1.3k 阅读✓ 已解决
3 回答2.7k 阅读✓ 已解决
6 回答1.3k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决