title: Using JS setTimeout to post AJAX requests in a loop, but setTimeout gets called far too often
body: <p>This question has been answered. The problem was that myEventMoveTrainManaul() was being called from other locations within the code. Thanks to everyone who offered their help.</p>
  
  <p>Please forgive me for re-posting this, but it was getting almost no attention and it's very important that I find someone to help me with this. Thank you for your kind understanding.  </p>
  
  <p>I have been working on a new feature for a facebook game I have written. The game allows a player to travel between cities in Europe by train and deliver goods for profit. This feature that I'm adding adds pathfinding AI to the game: it allows a player to select a city to travel to, then the game automatically moves the player's train along track from it's starting city to the destination city. I am using AJAX and setTimeout() to get the data from the backend and to enable the movement of the train along the track that connects cities. Please refer to the code which will (hopefully) contain a better understanding of what I am attempting to do.</p>
  
  <p>The problem is that setTimeout() gets called too often. I put a global variable called statusFinalDest which may contain two values: ENROUTE and ARRIVED. While the train is ENROUTE, the JS train movement function calls itself using setTimeout until the backend returns a statusFinalDest of ARRIVED, at which time the train movement timeout loop is (supposedly) terminated. However, instead of calling myEventMoveTrainManual() once for each turn the backend processes, it gets called exceedingly more often, as if it is not recognizing the changed state of statusFinalDest. I have attempted to put more limiting structures into the code to put an end to this excessive behavior, the they don't appear to be working.</p>
  
  <p>FYI - myEventMoveTrainManual() is not an event handler, but it does get called from an event handler.</p>
  
  <p>Here's the relevant FBJS (Facebook JS) code:</p>
  
  <pre><code>function myEventMoveTrainManual(evt) {
        if(mutexMoveTrainManual == 'CONTINUE') {
          //mutexMoveTrainManual = 'LOCKED';
          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) {
            statusFinalDest = data.status_final_dest;
            if(data.code != 'ERROR_FINAL_DEST') {
  
              // Draw train at new location
              trackAjax = new Ajax();
              trackAjax.responseType = Ajax.JSON;
              trackAjax.ondone = function(trackData) {
                var trains = [];
                trains[0] = trackData.train;
                removeTrain(trains);
                drawTrack(trackData.y1, trackData.x1, trackData.y2, trackData.x2, '#FF0', trains);
  
                if(data.code == 'UNLOAD_CARGO') {
                  unloadCargo();
                } else if (data.code == 'MOVE_TRAIN_AUTO' || data.code == 'TURN_END') {
                  moveTrainAuto();
                } else {
                  /* handle error */
                }
                mutexMoveTrainManual = 'CONTINUE';
              }
              trackAjax.post(baseURL + '/turn/get-track-data');
            }
          }
          ajax.post(baseURL + '/turn/move-train-set-destination', param);
        }
  
        // If we still haven't ARRIVED at our final destination, we are ENROUTE so continue
        // moving the train until final destination is reached
        // statusFinalDest is a global var
        if(statusFinalDest == 'ENROUTE') {
          setTimeout(myEventMoveTrainManual, 1000);
        }
  }
  </code></pre>
  
  <p>And here is the backend PHP code:</p>
  
  <pre><code>  public function moveTrainSetDestinationAction() {
      require_once 'Train.php';
      $trainModel = new Train();
  
      $userNamespace = new Zend_Session_Namespace('User');
      $gameNamespace = new Zend_Session_Namespace('Game');
  
      $this-&gt;_helper-&gt;layout()-&gt;disableLayout();
      $this-&gt;_helper-&gt;viewRenderer-&gt;setNoRender();
  
      $trainRow = $trainModel-&gt;getTrain($userNamespace-&gt;gamePlayerId);
      $statusFinalDest = $trainRow['status_final_dest'];
      if($statusFinalDest == 'ARRIVED') {
        $originCityId = $trainRow['dest_city_id'];
        $destCityId = $this-&gt;getRequest()-&gt;getPost('city_id');
        if(empty($destCityId)) {
          // If we arrived at final dest but user supplied no city then this method got called
          // incorrectly so return an error
          echo Zend_Json::encode(array('code' =&gt; 'ERROR_FINAL_DEST', 'status_final_dest' =&gt; $statusFinalDest));
          exit;
        }
  
        $gameNamespace-&gt;itinerary = $this-&gt;_helper-&gt;getTrainItinerary($originCityId, $destCityId);
        array_shift($gameNamespace-&gt;itinerary); //shift-off the current train city location
        $trainModel-&gt;setStatusFinalDest('ENROUTE', $userNamespace-&gt;gamePlayerId);
        $statusFinalDest = 'ENROUTE';
      }
      $cityId = $trainRow['dest_city_id'];
      if($trainRow['status'] == 'ARRIVED') {
        if(count($gameNamespace-&gt;itinerary) &gt; 0) {
          $cityId = array_shift($gameNamespace-&gt;itinerary);
        }
      }
      $trainRow = $this-&gt;_helper-&gt;moveTrain($cityId);
      if(count($trainRow) &gt; 0) {
        if($trainRow['status'] == 'ARRIVED') {
          // If there are no further cities on the itinerary, we have arrived at our final destination
          if(count($gameNamespace-&gt;itinerary) == 0) {
            $trainModel-&gt;setStatusFinalDest('ARRIVED', $userNamespace-&gt;gamePlayerId);
            $statusFinalDest = 'ARRIVED';
          }
          echo Zend_Json::encode(array('code' =&gt; 'UNLOAD_CARGO', 'status_final_dest' =&gt; $statusFinalDest));
          exit;
          // Pass id for last city user selected so we can return user to previous map scroll postion
        } else if($trainRow['track_units_remaining'] &gt; 0) {
          echo Zend_Json::encode(array('code' =&gt; 'MOVE_TRAIN_AUTO', 'status_final_dest' =&gt; $statusFinalDest));
          exit;
        } else { /* Turn has ended */
          echo Zend_Json::encode(array('code' =&gt; 'TURN_END', 'status_final_dest' =&gt; $statusFinalDest));
          exit;
        }
      }
      echo Zend_Json::encode(array('code' =&gt; 'MOVE_TRAIN_AUTO_ERROR'));
    }
  </code></pre>
  
  <p>Based on @brad's suggestion, I have modified myEventMoveTrainManual() as follows:</p>
  
  <pre><code>function myEventMoveTrainManual(evt) {
  //debugger;
        if(mutexMoveTrainManual == 'CONTINUE') {
          //mutexMoveTrainManual = 'LOCKED';
          //statusFinalDest = 'ARRIVED';
          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) {
  
            statusFinalDest = data.status_final_dest;
  //debugger;
  consoleLog('statusFinalDest='+statusFinalDest+', data.code='+data.code);
            if(data.code != 'ERROR_FINAL_DEST') {
  consoleLog('data.code != ERROR_FINAL_DEST');
              // Draw train at new location
              trackAjax = new Ajax();
              trackAjax.responseType = Ajax.JSON;
              trackAjax.ondone = function(trackData) {
  consoleLog('drawing track');
                var trains = [];
                trains[0] = trackData.train;
                removeTrain(trains);
                drawTrack(trackData.y1, trackData.x1, trackData.y2, trackData.x2, '#FF0', trains);
  consoleLog('processing data.code = '+data.code);
                if(data.code == 'UNLOAD_CARGO') {
                  unloadCargo();
    consoleLog('returned from unloadCargo()');
                } else if (data.code == 'MOVE_TRAIN_AUTO' || data.code == 'TURN_END') {
                  moveTrainAuto();
    consoleLog('returned from moveTrainAuto()');
    /*
                } else if (data.code == 'TURN_END') {
    consoleLog('moveTrainManual::turnEnd');
                  turnEnd();
    */
                } else {
                  /* handle error */
                }
                mutexMoveTrainManual = 'CONTINUE';
  
                // If we still haven't ARRIVED at our final destination, we are ENROUTE so continue
                // moving the train until final destination is reached
                if(statusFinalDest == 'ENROUTE') {
                  myEventMoveTrainManual(null);
                }
              }
              trackAjax.post(baseURL + '/turn/get-track-data');
            }
          }
          ajax.post(baseURL + '/turn/move-train-set-destination', param);
        }
  
        // If we still haven't ARRIVED at our final destination, we are ENROUTE so continue
        // moving the train until final destination is reached
        //if(statusFinalDest == 'ENROUTE') {
        //  clearTimeout(timerId);
        //  timerId = setTimeout(myEventMoveTrainManual, 1000);
        //}
  }
  </code></pre>
  
  <p>However, the original problem still manifests: myEventMoveTrainManual() gets called too many times.</p>