我遇到了这个问题,我创建的循环没有返回值。
这个想法很简单——我需要从一秒到一秒更新我的火车到达了多远。如果达到滚动的秒数,则意味着它正在前往车站的途中,或者正好在车站中。这是我的代码,如下。
谢谢,希望我不会错过这个帖子。
function Train(speed, distance, elapsedTime, eTA, station, condition, type) {
this.speed = speed;
this.station = station;
this.distance = distance;
this.elapsedTime = elapsedTime;
this.eTA = eTA;
this.condition = condition;
this.type = this.speed == 30 ? 'Regio' : this.speed == 70 ? 'Inter-Regio' : 'Broken';
}
var trainOne = new Train(30, '', '', '', '', '', '');
var elapsedTime =
function theLoop (elapsedTime) {
setTimeout (function(){
switch(elapsedTime){
case elapsedTime == 0:
Train().station = 'Station A';
Train().eTA = 28 - elapsedTime + 'seconds left untill reaching the next station';
break;
case elapsedTime < 28:
Train().station = 'Train left station A';
Train().eTA = 28 - elapsedTime + 'seconds left untill reaching the next station';
break;
case elapsedTime == 28:
Train().station = 'Station 2';
Train().eTA = 28 - elapsedTime + 'seconds left untill reaching the next station';
break;
case elapsedTime > 28 && elapsedTime < 70:
Train().station = 'Train left station 2';
Train().eTA = 70 - elapsedTime + 'seconds left untill reaching the next station';
break;
case elapsedTime == 70:
Train().station = 'Station 3';
Train().eTA = 84 - elapsedTime + 'seconds left untill reaching the next station';
break;
default :
Train().station = 'Station A';
Train().eTA = 'No information available yet';
}
console.log(trainOne);
if (++elapsedTime && elapsedTime < 12) {
theLoop(elapsedTime);
}
}, 1000);
} (0);
尝试另一个:
function Train(speed, distance, elapsedTime, eTA, station, condition, type) {
this.speed = speed;
this.station = station;
this.distance = distance;
this.elapsedTime = elapsedTime;
this.eTA = eTA;
this.condition = condition;
this.type = this.speed == 30 ? 'Regio' : this.speed == 70 ? 'Inter-Regio' : 'Broken';
let timerID = null;
this.run = function() {
timerID = setInterval((self) => {
self.elapsedTime++;
self.distance += speed;
console.log(`${self.elapsedTime} seconds, distance: ${self.distance}`);
}, 1000, this);
}
this.stop = function() {
console.log("Stop");
clearInterval(timerID);
}
this.pause = function() {
clearInterval(timerID);
}
this.station = function(name, duration) {
console.log(`Station ${name}`);
this.pause();
setTimeout((self) => {
console.log(`Live station ${name}`);
self.run();
}, duration, this, name);
}
}
var trainOne = new Train(30, 0, '', 0, '', '', '');
trainOne.run();
setTimeout(() => {
trainOne.station("A", 5000);
}, 5000);
setTimeout(() => {
trainOne.station("B", 5000);
}, 15000);
setTimeout(() => {
trainOne.stop();
}, 30000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句