我有一个我想要一个接一个地执行的操作列表。假设我们有一个拳击包锻炼:
哔哔声响起,然后 2 秒后教练告诉运动员该做什么("步法"(。15秒后,教练告诉运动员改变他正在做的事情("技术"(...这种情况一直持续到一分钟过去。然后,讲师重复此过程 3 次。
我正在尝试构建一些完全可以做到这一点的库,但是每个操作之间的延迟都遇到了问题。这是我到目前为止所做的:
class Action{
constructor(name = "Action", actualAction){
this.name = name;
this.actualAction = actualAction;
}
run(){
console.log("Executing Action: " + this.name);
this.actualAction();
}
}
function repeat(times){
var timesLeft = times;
return function(){
timesLeft--;
return timesLeft > 0;
}
}
class SleepAction extends Action{
constructor(ms, nextAction){
super("Sleep " + ms);
this.ms = ms;
this.nextAction = nextAction;
}
run(){
setTimeout(this.nextAction.run(), this.ms);
}
}
class Block extends Action{
constructor(name = "Block", actions, repeat){
super(name);
this.repeat = repeat;
this.instructions = actions;
}
run(){
this.instructions.forEach(function(action) {
action.run();
});
if(this.repeat()){
this.run();
}
}
}
您可以说我正在使用 setTimeout 来尝试使其工作,但在此示例中所有操作同时运行:
var doNothing = new Action("Nothing", function(){});
var boxingBagPreset = new Block("Boxing Bag 15-15-15-15 3 Times",
[beepAction,
new SleepAction(2000, new Block("Tiny Pause", [
new Action("FOOTWORK", textToSpeech("FOOTWORK")),
new SleepAction(15000, new Block("Sleep 15", [
new Action("SPEED", textToSpeech("SPEED")),
new SleepAction(15000, new Block("Sleep 15", [
new Action("POWER", textToSpeech("POWER")),
new SleepAction(15000, new Block("Sleep 15", [
new Action("REST", textToSpeech("REST")),
new SleepAction(15000, new Block("Sleep 15", [doNothing], repeat(1)))
], repeat(1)))
], repeat(1)))
] , repeat(1)))
], repeat(1)))],
repeat(3));
我需要更改什么才能使其正常工作?
问题是您立即调用函数并传递结果,而不是将函数本身传递给setTimeout
。
试试这个:
class SleepAction extends Action{
constructor(ms, nextAction){
super("Sleep " + ms);
this.ms = ms;
this.nextAction = nextAction;
}
run(){
var func = () => this.nextAction.run();
setTimeout(func, this.ms);
}
}
由于this
的处理方式,您不能只传递this.nextAction.run
因为this
在调用它时会有所不同setTimeout
。
在此示例中,我创建了一个新函数来捕获this
。