gpt4 book ai didi

javascript - 以它们之间的延迟运行操作

转载 作者:行者123 更新时间:2023-11-30 15:15:23 25 4
gpt4 key购买 nike

我有一个要一个接一个执行的 Action 列表。假设我们有一个拳击袋训练:

发出一声哔哔声,2 秒后教练告诉运动员该做什么(“FOOTWORK”)。 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

关于javascript - 以它们之间的延迟运行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44548754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com