views:

37

answers:

1

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 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.

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.

Here's the relevant FBJS (Facebook JS) 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);
      }
}

And here is the backend PHP code:

  public function moveTrainSetDestinationAction() {
    require_once 'Train.php';
    $trainModel = new Train();

    $userNamespace = new Zend_Session_Namespace('User');
    $gameNamespace = new Zend_Session_Namespace('Game');

    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender();

    $trainRow = $trainModel->getTrain($userNamespace->gamePlayerId);
    $statusFinalDest = $trainRow['status_final_dest'];
    if($statusFinalDest == 'ARRIVED') {
      $originCityId = $trainRow['dest_city_id'];
      $destCityId = $this->getRequest()->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' => 'ERROR_FINAL_DEST', 'status_final_dest' => $statusFinalDest));
        exit;
      }

      $gameNamespace->itinerary = $this->_helper->getTrainItinerary($originCityId, $destCityId);
      array_shift($gameNamespace->itinerary); //shift-off the current train city location
      $trainModel->setStatusFinalDest('ENROUTE', $userNamespace->gamePlayerId);
      $statusFinalDest = 'ENROUTE';
    }
    $cityId = $trainRow['dest_city_id'];
    if($trainRow['status'] == 'ARRIVED') {
      if(count($gameNamespace->itinerary) > 0) {
        $cityId = array_shift($gameNamespace->itinerary);
      }
    }
    $trainRow = $this->_helper->moveTrain($cityId);
    if(count($trainRow) > 0) {
      if($trainRow['status'] == 'ARRIVED') {
        // If there are no further cities on the itinerary, we have arrived at our final destination
        if(count($gameNamespace->itinerary) == 0) {
          $trainModel->setStatusFinalDest('ARRIVED', $userNamespace->gamePlayerId);
          $statusFinalDest = 'ARRIVED';
        }
        echo Zend_Json::encode(array('code' => 'UNLOAD_CARGO', 'status_final_dest' => $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'] > 0) {
        echo Zend_Json::encode(array('code' => 'MOVE_TRAIN_AUTO', 'status_final_dest' => $statusFinalDest));
        exit;
      } else { /* Turn has ended */
        echo Zend_Json::encode(array('code' => 'TURN_END', 'status_final_dest' => $statusFinalDest));
        exit;
      }
    }
    echo Zend_Json::encode(array('code' => 'MOVE_TRAIN_AUTO_ERROR'));
  }
+2  A: 

If the function myEventMoveTrainManual is being called from an event handler, you're going to end up with a new timer running each time the event occurs.

One simple hack that should help is to kill the timer before starting a new one:

var timerId;

//...
clearTimeout(timerId);
timerId = setTimeout(myEventMoveTrainManual, 1000);
//...

But I think what you really want to do is call a different function, one that checks if your timer loop is already running, and if not, calls myEventMoveTrainManual.

sje397
Thanks for responding so promptly. I added clearTimeout() to my code. It did improve things, but it did not solve my main problem. Now I've realized that I have another problem: all of these excessive function calls are exaggerating my turn count by calling turnEnd() too often. This is a serious problem. Anyway, thank you for your help.
Chris Barnhill