需要延迟javascript的执行,但是setTimeout被证明是有问题的

Need to delay javascript execution, but setTimeout is proving problematic

本文关键字:setTimeout 证明是 有问题 但是 执行 延迟 javascript      更新时间:2023-09-26

感谢您花时间帮助我。

我正在写一个游戏,在这个游戏中,一个动画火车图标沿着给定的路径移动到目的地,并在途中的停靠点停留。这是为了给人一种动画的印象。

游戏是用Facebook Javascript编写的。我需要想办法让火车图标暂停1秒,然后再转到下一个航路点。我希望找到一个可以让我暂停脚本执行一秒钟的函数,但JS中似乎不存在这样的函数。所以我尝试了setTimeout,但我的主要问题有两个:

  1. 我需要将一个数组作为参数传递到回调函数中,但我不知道如何使setTimeout执行此操作。

  2. 我终于成功地使用setTimeout为5个路点执行了我的火车动画代码(我在1中通过使用全局变量克服了这个问题)。不幸的是,似乎对setTimeout的所有五个调用几乎同时排队,这导致等待第一个setTimeout启动一秒钟,然后它们都同时启动,破坏了火车动画的效果。

我已经连续六个小时在和这个问题作斗争了。如果有人能帮我找到解决方案,那就太好了。谢谢

这是代码:

function myEventMoveTrainManual(evt, performErrorCheck) {
      if(mutexMoveTrainManual == 'CONTINUE') {
        var ajax = new Ajax();
        var param = {};
        if(evt) {
          var cityId = evt.target.getParentNode().getId();
          var param = { "city_id": cityId };
        }
        ajax.responseType = Ajax.JSON;
        ajax.ondone = function(data) {
            var actionPrompt = document.getElementById('action-prompt');
            actionPrompt.setInnerXHTML('<span><div id="action-text">'+
              'Train en route to final destination...</div></span>');
            for(var i = 0; i < data.length; i++) {
              statusFinalDest = data[i]['status_final_dest'];
               //pause(1000);
               gData = data[i];
               setTimeout(function(){drawTrackTimeout()},1000);
              if(data[i]['code'] == 'UNLOAD_CARGO' && statusFinalDest == 'ARRIVED') {
                unloadCargo();
              } else if (data[i]['code'] == 'MOVE_TRAIN_AUTO' || data[i]['code'] == 'TURN_END') {
                //moveTrainAuto();
              } else {
                // handle error 
              }
              mutexMoveTrainManual = 'CONTINUE';
            }  
        }
        ajax.post(baseURL + '/turn/move-train-final-dest', param);
      }
}

function drawTrackTimeout() {
  var trains = [];
  trains[0] = gData['train'];
  removeTrain(trains);
  drawTrack(gData['y1'], gData['x1'], gData['y2'], gData['x2'], '#FF0', trains);
  gData = null;
}

通常情况下,这将通过创建一个对象(称为myTrain)来完成,该对象具有自己的所有数据和方法,然后调用myTrain.runmehod来查看列车的位置。如果列车在两个车站之间,它会用setTimeout调用自己,并延迟50ms。当它到达一个电台时,它会在1000ms内呼叫自己,在电台产生1秒的停顿。

如果同时对setTimeouts进行排队,则可能会导致它们全部被其他进程延迟,然后全部同时运行。

嘿,有点好玩(小心包装)。需要一些良好的ole原型继承实践:

<!-- All the style stuff should be in a rule -->
<div style="position: relative; border: 1px solid blue;">
  <div id="redTrain"
   style="width:10px;height:10px;background-color:red; position:absolute;top:0px;left:0px;"></div>
</div>
<script type="text/javascript">
// Train constructor
function Train(id) {
  this.element = document.getElementById(id);
  this.timerId;
}
// Methods
// Trivial getPos function
Train.prototype.getPos = function() {
  return this.element.style.left;
}
// Trivial setPos function
Train.prototype.setPos = function(px) {
  this.element.style.left = parseInt(px,10) + 'px';
}
// Move it px pixels to the right
Train.prototype.move = function(px) {
  this.setPos(px + parseInt(this.getPos(),10));
}
// Recursive function using setTimeout for animation
// Probably should accept a parameter for lag, long lag
// should be a multiple of lag
Train.prototype.run = function() {
  // If already running, stop it
  // so can interrupt a pause with a start
  this.stop();
  // Move the train
  this.move(5);
  // Keep a reference to the train for setTimeout
  var train = this;
  // Default between each move is 50ms
  var lag = 50;
  // Pause for 1 second each 100px
  if (!(parseInt(this.getPos(),10) % 100)) {
    lag = 1000;
  }
  train.timerId = window.setTimeout( function(){train.run();}, lag);
}
// Start should do a lot more initialising
Train.prototype.start = function() {
  this.run();
}
// Stops the train until started again
Train.prototype.stop = function() {
  if (this.timerId) {
    clearTimeout(this.timerId);
  }
}
// Set back to zero
Train.prototype.reset = function() {
  this.stop();
  this.setPos(0);
}
// Initialise train here
var myTrain = new Train('redTrain');
</script>
<p>&nbsp;</p>
<button onclick="myTrain.start();">Start the train</button>
<button onclick="myTrain.stop();">Stop the train</button>
<button onclick="myTrain.reset();">Reset the train</button>

要传递参数,这可能会对您有所帮助:

setTimeout(function() {
    (function(arg1, arg2) {
        // you can use arg1 / arg2 here
    })('something', 123);
}, 1000);

或者,如果您使用定义的函数:

setTimeout(function() {
    someFunction('something', 123);
}, 1000);

它基本上启动了一个超时;一秒钟后,使用指定的参数调用函数。

使用OO原理来简化问题如何?创建一个具有以下方法的"对象"列车:

//train obj
function Train(){
   this.isOnWaypoint = function(){
     return calculateIsWayPoint()
   }
}
//main logic
var train = new Train()
var doneWaiting = false
var doneWaitingTimeout = undefined
var gameLoop = setInterval(1000,function(){
   ...
   if(train.isOnWaypoint() && !doneWaiting){
     if(doneWaitingTimeout == undefined){
       setTimeOut(5000,function(){
         doneWaiting = true
         doneWaitingTimeout = undefined
       })
     }
   }
   ...
})

这是我最终提出的解决方案:

function drawTrackTimeout() {
  if(gData != null && gIndex < gData.length) {
    var trains = [];
    trains[0] = gData[gIndex]['train'];
    removeTrain(trains);
    drawTrack(gData[gIndex]['y1'], gData[gIndex]['x1'], gData[gIndex]['y2'], gData[gIndex]['x2'], '#FF0', trains);
    statusFinalDest = gData[gIndex]['status_final_dest'];
    if(statusFinalDest == 'ARRIVED') {
      unloadCargo();
    } else if (gData[gIndex]['code'] == 'MOVE_TRAIN_AUTO' || gData[gIndex]['code'] == 'TURN_END') {
      //moveTrainAuto();
    } else {
      // handle error 
    }
    gIndex++;
  } else {
    clearInterval(gIntid);
    gIntid = null;
    gData = null;
    gIndex = 0;
  }
}

function myEventMoveTrainManual(evt, performErrorCheck) {
//debugger;
      if(mutexMoveTrainManual == 'CONTINUE') {
        var ajax = new Ajax();
        var param = {};
        if(evt) {
          var cityId = evt.target.getParentNode().getId();
          var param = { "city_id": cityId };
        }
        ajax.responseType = Ajax.JSON;
        ajax.ondone = function(data) {
            var actionPrompt = document.getElementById('action-prompt');
            actionPrompt.setInnerXHTML('<span><div id="action-text">'+
              'Train en route to final destination...</div></span>');
            gData = data;
            gIndex = 0;            
            gIntid = setInterval(function(){drawTrackTimeout()},1000);              
        }
        ajax.post(baseURL + '/turn/move-train-final-dest', param);
      }
}