为什么在循环结束之前不调用 setInterval



在我的游戏循环中,我想问三个问题。之后,应该调用一个setInterval来处理这三个问题的答案。这个间隔结束后,我想再重复这个过程3次。然而,当循环开始时,它会遍历问题3次,然后执行setInterval部分。

编辑:用英语重写所有内容。

//require "prompt-sync"
const prompt = require("prompt-sync")({ sigint: true });
//Auto class
class Car{
constructor(brand, speed, maxSpeed, currentSpeed){
this.carBrand = brand;
this.carSpeed = speed;
this.carMaxSpeed = maxSpeed;
this.carCurrentSpeed = currentSpeed;
}
drive(){
if(this.carCurrentSpeed >= this.carMaxSpeed){
clearInterval(inter);
console.log("too fast");
}else{
this.carCurrentSpeed = this.carCurrentSpeed + this.carSpeed;
console.log(this.carBrand + " has a speed of " + this.currentSpeed + " km/h");
}
}    
}

//gameloop
for(var i = 0; i < 3; i++){
//infos from usr
let brand = prompt("what brand is your car? ");
let speed = parseInt(prompt("How much speed does your car gain per second? "));
let maxSpeed = parseInt(prompt("what is the maximum speed of your car? "));

//create Object
var usrAuto = new Car(brand, speed, maxSpeed, 0);
//setInterval
var inter = setInterval(usrAuto.plus.bind(usrAuto), 1000);

新答案:您希望代码运行该间隔,并在完成后继续执行代码。它不起作用,因为setInterval不会停止代码,它生成了一个异步任务,将在每个延迟集上运行。

你能做的只是一个简单的while循环;睡眠;持续1秒。由于JavasScript上不存在睡眠,因此有一些方法可以创建一个新的睡眠,下面是最简单的方法之一。

const prompt = require("prompt-sync")({ sigint: true });
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
//Auto class
class Car{
constructor(brand, speed, maxSpeed, currentSpeed){
this.carBrand = brand;
this.carSpeed = speed;
this.carMaxSpeed = maxSpeed;
this.carCurrentSpeed = currentSpeed;
this.crashed = false;
}
drive(){
if(this.carCurrentSpeed >= this.carMaxSpeed){
console.log("too fast");
this.crashed= true;
}else{
this.carCurrentSpeed = this.carCurrentSpeed + this.carSpeed;
console.log(this.carBrand + " has a speed of " + this.carCurrentSpeed + " km/h");
}
}    
}
var cars = []
//gameloop
for(var i = 0; i < 3; i++){
//infos from usr
let brand = prompt("what brand is your car? ");
let speed = parseInt(prompt("How much speed does your car gain per second? "));
let maxSpeed = parseInt(prompt("what is the maximum speed of your car? "));

//create Object
var usrAuto = new Car(brand, speed, maxSpeed, 0);
while (usrAuto.crashed == false){
usrAuto.drive()
sleep(1000)
}
}

最新更新