Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 949859
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T23:28:13+00:00 2026-05-15T23:28:13+00:00

This question has been answered. The problem was that myEventMoveTrainManaul() was being called from

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T23:28:14+00:00Added an answer on May 15, 2026 at 11:28 pm

    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…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I realize that this question has been asked and has been answered here but
This question has been answered. I've improved the code a bit (at least I
Preamble So, this question has already been answered, but as it was my first
I know this question has been asked before, but I ran into a problem.
Being new to test based development, this question has been bugging me. How much
I saw this same question for VIM and it has been something that I
Edit: While this question has been asked and answered before ( 1 ), (
I'm sure this question has been answered before, but I don't think I'm using
I know this question has been asked and answered in several ways, but none
I am sure this question has been asked and answered; but I haven't managed

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.