views:

115

answers:

3

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.

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.

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.

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.

FYI - myEventMoveTrainManual() is not an event handler, but it does get called from an event handler.

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'));
  }

Based on @brad's suggestion, I have modified myEventMoveTrainManual() as follows:

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);
      //}
}

However, the original problem still manifests: myEventMoveTrainManual() gets called too many times.

A: 

I am not sure of the code but, but problem seems like this:

You are checking if statusFinalDest == 'ENROUTE' at the client side, which does not work.

Place a timer based counter on the server side before setting the global value to ENROUT and not setting it every time ie set 1 sec delay in setting the value also, as any client side method would get overridden by a fresh copy of js code.

loxxy
Thanks for your input. You are correct: my logic is faulty. I have a few questions for you: what should the server side counter count? How would this fix my problem? I think you have valuable input, but I would appreciate it if you would elaborate a bit more on it. Thanks :)
Chris Barnhill
A: 

Your Ajax-calls are asynchronous. I think even if the back end is ready, the response needs some time to get back to the client. Meanwhile the client sends more Ajax-requests.
(edit: Your changes approve that this is not the problem)

  • it seems that you registered an event listener for a DOM-event like mouse-click, because you are checking the evt-argument.
    Please post the code of your event handler and the part of the code, where you register the event.

  • Who says that there are too much calls? I can't see count-variables in the server/client scripts; Note that log-items are sometimes added very late to the console, they are not a indicator to my eyes.
    I think it's very important to know your indicators!

fishbone
A: 

you need your setTimeout to be within the callback of your ajax call (ajax.onDone if I'm reading this correctly)

I'm assuming you want your ajax call to be called again only after the first call has completed. Currently, this code will execute your function once a second, unconcerned with the pending asynchronous calls.

Is that what you want? Or do you want it to be executed one second after your ajax returns? If the latter, put your setTimeout within that callback and you'll only get the next request 1s after your ajax returns.

edit with adjusted example:

I still don't see your setTimeout within the ajax call. Here's some pseudo code and an explanation:

function myFunc(){

  var ajax = new Ajax();
  ajax.onDone = function(data){
    // do some stuff here (ie modify mutex)

    // now trigger your setTimeout within this onDone to call myFunc() again:
    setTimeout(myFunc,1000);
  }

  ajax.post("someURL")
}

explanation Here's what happens, you call myFunc(), it instantiates your ajax object and makes the call. When that ajax returns, you do whatever you want to do, then call myFunc() again (the setTimeout) after x amount of milliseconds (inside onDone). This instantiates your ajax object and makes the call...

brad
Yes, you have described exactly what I am attempting. OK, so I will put the setTimeout within the callback function. But here's my next question: since the callback function needs to be executed mutliple times until statusFinalDest == 'ARRIVED', will putting setTimeout inside the callback facilitate this?
Chris Barnhill
If you review my latest edit of the question, you will find that I have implemented your suggested fix. Unfortunately, it did not change anything which greatly perplexes me. I would have thought that calling myEventMoveTrainManual() from the call back instead of setTimeout would result in a profound change, but the app is behaving as if nothing has changed.
Chris Barnhill
see update.....
brad