Synchronous Call in JavaScript is not working - javascript

I am creating a hotel page which contains all the details of hotels including its reviews. For the reviews of the hotel, i want to do pagination.
In my code, init() function contain all the code for performing initial calculations like calculating no of pages etc.
As you can see init() is calling a function getReviewList which will return list of reviews. In getReviewList(), making a synchronous call to receive lists of reviews(i.e. reviewList.json).
The goal is once i receive the list of reviews, i can perform all the calculations. Even i am using setTimeout function so that this action get delayed by some time and in this mean time, the response get stored in the global variable "reviewList".
But the problem is that the calculation part gets executed before the response is stored in the global variable "reviewList". Please guide me where i am going wrong.
Javascript (fiddle : http://jsfiddle.net/n28SS/) fiddle contains incomplete code
getReviewList: function () {
var myReq, reqJSON,
oThis = this;
if(window.XMLHttpRequest) {
myReq = new XMLHttpRequest();
} else {
myReq = new ActiveXObject("Microsoft.XMLHTTP");
}
myReq.open("GET", "reviewList.json", true);
myReq.send();
myReq.onreadystatechange = function() {
if (myReq.readyState == 4) {
if (myReq.status == 200) {
oThis.reviewList = JSON.parse(myReq.responseText);
}
}
}
},
init: function() {
var oThis = this,
records;
records = oThis.getReviewList();
setTimeout(function () {
records = oThis.reviewList.length;
}, 1000);
oThis.pages = Math.ceil(records / oThis.itemsPerPage);
oThis.inited = true;
oThis.attachEventListener();
},

This doesn't work because
setTimeout(function () {
records = oThis.reviewList.length;
}, 1000);
returns immediately and performs the records=... operation in the background after 1000 ms.
The following line executes immediately and hence doesn't have access to records variable
oThis.pages=Math.ceil(records/...)
which will become available 1sec later. You can either move all the code into the set timeout block, or better yet make everything asynchronous:
getReviewList: function (callback) {//pass the function that needs to act on list
var myReq, reqJSON,
oThis = this;
if(window.XMLHttpRequest) {
myReq = new XMLHttpRequest();
} else {
myReq = new ActiveXObject("Microsoft.XMLHTTP");
}
myReq.open("GET", "reviewList.json", true);
myReq.send();
myReq.onreadystatechange = function() {
if (myReq.readyState == 4) {
if (myReq.status == 200) {
oThis.reviewList = JSON.parse(myReq.responseText);
callback(oThis.reviewList);
}
}
}
},
init: function() {
var oThis = this,
records;
records = oThis.getReviewList(function (reviewList) { //Pass the function as a parameter
records = reviewList.length;
oThis.pages = Math.ceil(records / oThis.itemsPerPage);
oThis.inited = true;
oThis.attachEventListener();
});
},
I haven't tested the code but it should demonstrate the basic concept.

Related

Trying to convert existing synchronous XmlHttpRequest object to be asynchronous to keep up with current fads

Soo, I keep getting slammed with cautions from Chrome about how synchronous XmlHttpRequest calls are being deprecated, and I've decided to have a go at trying to convert my use-case over in order to keep up with this fad...
In this case, I have an ~9 year old JS object that has been used as the central (and exemplary) means of transporting data between the server and our web-based applications using synchronous XHR calls. I've created a chopped-down version to post here (by gutting out a lot of sanity, safety and syntax checking):
function GlobalData()
{
this.protocol = "https://";
this.adminPHP = "DataMgmt.php";
this.ajax = false;
this.sessionId = "123456789AB";
this.validSession = true;
this.baseLocation = "http://www.example.com/";
this.loadResult = null;
this.AjaxPrep = function()
{
this.ajax = false;
if (window.XMLHttpRequest) {
try { this.ajax = new XMLHttpRequest(); } catch(e) { this.ajax = false; } }
}
this.FetchData = function (strUrl)
{
if ((typeof strURL=='string') && (strURL.length > 0))
{
if (this.ajax === false)
{
this.AjaxPrep();
if (this.ajax === false) { alert('Unable to initialise AJAX!'); return ""; }
}
strURL = strURL.replace("http://",this.protocol); // We'll only ask for data from secure (encrypted-channel) locations...
if (strURL.indexOf(this.protocol) < 0) strURL = this.protocol + this.adminPHP + strURL;
strURL += ((strURL.indexOf('?')>= 0) ? '&' : '?') + 'dynamicdata=' + Math.floor(Math.random() * this.sessionId);
if (this.validSession) strURL += "&sessionId=" + this.sessionId;
this.ajax.open("GET", strURL, false);
this.ajax.send();
if (this.ajax.status==200) strResult = this.ajax.responseText;
else alert("There was an error attempting to communicate with the server!\r\n\r\n(" + this.ajax.status + ") " + strURL);
if (strResult == "result = \"No valid Session information was provided.\";")
{
alert('Your session is no longer valid!');
window.location.href = this.baseLocation;
}
}
else console.log('Invalid data was passed to the Global.FetchData() function. [Ajax.obj.js line 62]');
return strResult;
}
this.LoadData = function(strURL)
{
var s = this.FetchData(strURL);
if ((s.length>0) && (s.indexOf('unction adminPHP()')>0))
{
try
{
s += "\r\nGlobal.loadResult = new adminPHP();";
eval(s);
if ((typeof Global.loadResult=='object') && (typeof Global.loadResult.get=='function')) return Global.loadResult;
} catch(e) { Global.Log("[AjaxObj.js] Error on Line 112: " + e.message); }
}
if ( (typeof s=='string') && (s.trim().length<4) )
s = new (function() { this.rowCount = function() { return -1; }; this.success = false; });
return s;
}
}
var Global = new GlobalData();
This "Global" object is referenced literally hundreds of times across 10's of thousands of lines code as so:
// Sample data request...
var myData = Global.LoadData("?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc");
if ((myData.success && (myData.rowCount()>0))
{
// Do Stuff...
// (typically build and populate a form, input control
// or table with the data)
}
The server side API is designed to handle all of the myriad kinds of requests encountered, and, in each case, to perform whatever magic is necessary to return the data sought by the calling function. A sample of the plain-text response to a query follows (the API turns the result(s) from any SQL query into this format automatically; adjusting the fields and data to reflect the retrieved data on the fly; the sample data below has been anonymized;):
/* Sample return result (plain text) from server:
function adminPHP()
{
var base = new DataInterchangeBase();
this.success = true;
this.colName = function(idNo) { return base.colName(idNo); }
this.addRow = function(arrRow) { base.addRow(arrRow); }
this.get = function(cellId,rowId) { return base.getByAbsPos(cellId,rowId); }
this.getById = function(cellId,rowId) { return base.getByIdVal(cellId,rowId); }
this.colExists = function(colName) { return ((typeof colName=='string') && (colName.length>0)) ? base.findCellId(colName) : -1; }
base.addCols( [ 'id','email','firstName','lastName','namePrefix','nameSuffix','phoneNbr','companyName' ] );
this.id = function(rowId) { return base.getByAbsPos(0,rowId); }
this.email = function(rowId) { return base.getByAbsPos(1,rowId); }
this.firstName = function(rowId) { return base.getByAbsPos(2,rowId); }
this.lastName = function(rowId) { return base.getByAbsPos(3,rowId); }
this.longName = function(rowId) { return base.getByAbsPos(5,rowId); }
this.namePrefix = function(rowId) { return base.getByAbsPos(6,rowId); }
this.nameSuffix = function(rowId) { return base.getByAbsPos(7,rowId); }
this.companyName = function(rowId) { return base.getByAbsPos(13,rowId); }
base.addRow( [ "2","biff#nexuscons.com","biff","broccoli","Mr.","PhD","5557891234","Nexus Consulting",null ] );
base.addRow( [ "15","happy#daysrhere.uk","joseph","chromebottom","Mr.","","5554323456","Retirement Planning Co.",null ] );
base.addRow( [ "51","michael#sunrisetravel.com","mike","dolittle","Mr.","",""5552461357","SunRise Travel",null ] );
base.addRow( [ "54","info#lumoxchemical.au","patricia","foxtrot","Mrs,","","5559876543","Lumox Chem Supplies",null ] );
this.query = function() { return " SELECT `u`.* FROM `users` AS `u` WHERE (`deleted`=0) ORDER BY `u`.`lastName` ASC, `u`.`firstName` LIMIT 4"; }
this.url = function() { return "https://www.example.com/DataMgmt.php?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc&dynamicdata=13647037920&sessionId=123456789AB\"; }
this.rowCount = function() { return base.rows.length; }
this.colCount = function() { return base.cols.length; }
this.getBase = function() { return base; }
}
*/
In virtually every instance where this code is called, the calling function cannot perform its work until it receives all of the data from the request in the object form that it expects.
So, I've read a bunch of stuff about performing the asynchronous calls, and the necessity to invoke a call-back function that's notified when the data is ready, but I'm a loss as to figuring out a way to return the resultant data back to the original (calling) function that's waiting for it without having to visit every one of those hundreds of instances and make major changes in every one (i.e. change the calling code to expect a call-back function as the result instead of the expected data and act accordingly; times 100's of instances...)
Sooo, any guidance, help or suggestions on how to proceed would be greatly appreciated!

How to deal with asyncronous javascript in loops?

I have a forloop like this:
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname);
myphone.get(function(phonenumbers){
if(myphone.phonearray){
myperson.save();
//Can I put a break here?;
}
});
}
What it does is that it searches for phone-numbers in a database based on various first-names. What I want to achieve is that once it finds a number associated with any of the first names, it performs myperson.save and then stops all the iterations, so that no duplicates get saved. Sometimes, none of the names return any phone-numbers.
myphone.get contains a server request and the callback is triggered on success
If I put a break inside the response, what will happen with the other iterations of the loop? Most likely the other http-requests have already been initiated. I don't want them to perform the save. One solution I have thought of is to put a variable outside of the forloop and set it to save, and then check when the other callbacks get's triggered, but I'm not sure if that's the best way to go.
You could write a helper function to restrict invocations:
function callUntilTrue(cb) {
var done = false;
return function () {
if (done) {
log("previous callback succeeded. not calling others.");
return;
}
var res = cb.apply(null, arguments);
done = !! res;
};
}
var myperson = {
firstname: {
"tom": null,
"jerry": null,
"micky": null
},
save: function () {
log("save " + JSON.stringify(this, null, 2));
}
};
var cb = function (myperson_, phonenumbers) {
if (myperson_.phonearray) {
log("person already has phone numbers. returning.");
return false;
}
if (phonenumbers.length < 1) {
log("response has no phone numbers. returning.");
return false;
}
log("person has no existing phone numbers. saving ", phonenumbers);
myperson_.phonearray = phonenumbers;
myperson_.save();
return true;
};
var restrictedCb = callUntilTrue(cb.bind(null, myperson));
for (var name in myperson.firstname) {
var myphone = new phone(myperson, name);
myphone.get(restrictedCb);
}
Sample Console:
results for tom-0 after 1675 ms
response has no phone numbers. returning.
results for jerry-1 after 1943 ms
person has no existing phone numbers. saving , [
"jerry-1-0-number"
]
save {
"firstname": {
"tom": null,
"jerry": null,
"micky": null
},
"phonearray": [
"jerry-1-0-number"
]
}
results for micky-2 after 4440 ms
previous callback succeeded. not calling others.
Full example in this jsfiddle with fake timeouts.
EDIT Added HTML output as well as console.log.
The first result callback will only ever happen after the loop, because of the single-threaded nature of javascript and because running code isn't interrupted if events arrive.
If you you still want requests to happen in parallel, you may use a flag
var saved = false;
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname /* name? */);
myphone.get(function(phonenumbers){
if (!saved && myphone.phonearray){
saved = true;
myperson.save();
}
});
}
This will not cancel any pending requests, however, just prevent the save once they return.
It would be better if your .get() would return something cancelable (the request itself, maybe).
var saved = false;
var requests = [];
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname /* name? */);
var r;
requests.push(r = myphone.get(function(phonenumbers){
// Remove current request.
requests = requests.filter(function(i) {
return r !== i;
});
if (saved || !myphone.phonearray) {
return;
}
saved = true;
// Kill other pending/unfinished requests.
requests.forEach(function(r) {
 r.abort();
});
myperson.save();
}));
}
Even better, don't start all requests at once. Instead construct an array of all possible combinations, have a counter (a semaphore) and only start X requests.
var saved = false;
var requests = [];
// Use requests.length as the implicit counter.
var waiting = []; // Wait queue.
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname /* name? */);
var r;
if (requests.length >= 4) {
// Put in wait queue instead.
waiting.push(myphone);
continue;
}
requests.push(r = myphone.get(function cb(phonenumbers){
// Remove current request.
requests = requests.filter(function(i) {
return r !== i;
});
if (saved) {
return;
}
if (!myphone.phonearray) {
// Start next request.
var w = waiting.shift();
if (w) {
requests.push(w.get(cb));
)
return;
}
saved = true;
// Kill other pending/unfinished requests.
requests.forEach(function(r) {
r.abort();
});
myperson.save();
}));
}

XMLHttpRequest - when returning responseText to another function, it returns undefined

SOLVED.
I changed my code into this:
function init() {
//preloadImages();
getContent('events', 'events');
getContent('content', 'main');
}
function loadingScreen(start) {
var loadingSpan = document.getElementById('loading');
if (start == true) {
loadingSpan.innerHTML = '<p>Loading...<br><img src="images/loading.gif"></p>';
}
else {
loadingSpan.innerHTML = '';
}
}
function getContent(what, where) {
if (what == 'content') {
loadingScreen(true);
var ranLoad = true;
}
var toSet = document.getElementById(what);
var location = "content/" + where + ".txt";
var request = new XMLHttpRequest;
request.open("GET", location, true);
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200){
toSet.innerHTML = request.responseText;
if (ranLoad==true){
loadingScreen(false);
}
}
}
request.send(null);
}
window.onload = init;
tl;dr or long-winded - see the code and the results below.
So. I am building a small webpage for a friend, and I decided to try out a technique where instead of writing the content directly in the webpage, I will use XMLHttpRequest to retrieve content (in the same domain), and place them in the content , where it will be updated by javascript, when people click on a different anchor.
Well, I came across a roadbump.
When I created the functions for getting the content (setEvents and setContent), where it creates a variable and calls a function for setting the variable (getMarkup), when the function was called, and the return statement was executed, it returns undefined. I found a thread similar, but their solution was to add the innerHTML statement DIRECTLY in the getMarkup function. I don't want to do that.
Here's the code and the results:
Edit: Esailija suggested that I should have just posted the code. To me it was a tad bit easier to just take the image, but here it is:
function init() {
//preloadImages();
setEvents();
setContent('main');
}
function setEvents() {
var eventDiv = document.getElementById("events");
var eventContent = getMarkup("content/events.txt");
eventDiv.innerHTML = eventContent;
}
function setContent(which) {
loadingScreen('start');
var contentDiv = document.getElementById('content');
location_ = "content/" + which + 'txt';
//var contentContent = getMarkup('location');
//contentDiv.innerHTML = contentContent;
loadingScreen('stop');
}
function loadingScreen(action) {
var loadingSpan = document.getElementById('loading');
loadingSpan.innerHTML = "Test";
if (action == 'start') {
loadingSpan.innerHTML = '<p>Loading...<br><img src="images/loading.gif"></p>';
}
if (action == 'stop') {
loadingSpan.innerHTML = '';
}
}
function getMarkup(where) {
var filerequest = new XMLHttpRequest();
filerequest.open("GET", where, true);
filerequest.onreadystatechange = function() {
if (filerequest.readyState == 4 && filerequest.status == 200) {
var test = document.getElementById("events");
var reply = filerequest.responseText;
//Doesn't work
return reply;
//Works just fine
//test.innerHTML = reply;
}
};
filerequest.send(null);
}
window.onload = init;
When I do the innerHTML instead of return it shows "Test TEST", and when I do return instead of innerHTML, it shown "undefined".
I really don't want to do the innerHTML part of it, so is there a workaround to make that return statement work?
Are you familiar with callbacks? Open up Firebug and put a breakpoint on your return reply; line - notice the call stack. The function where you have return reply; is not getMarkup.
Basically you're going to have to restructure your code a little. I would have getMarkup take an additional parameter - the DOM element to which you want to set its innerHTML value.
It seems that you don't quite understand how ajax works.
Once you call your getMarkup function, you send an ajax request and tell the browser to use the function after onreadystatechange to handle the reply. So actually when the reply is back, it's not your other functions like setContent that are calling that handler but the browser. That's why the return doesn't work.
Also when you call something like var contentContent = getMarkup('location'); , as getMarkup has no explicit return value, so by default contentContent gets undefined. You may think that it should get the return value inside your anonymous function but that's not the case. The getMarkup function returns immediately but the handler will be called only when the ajax response comes.
If you want to make that nice, you will have to do something extra like: you only have one ajax handler like you did. Once a function called that ajax function it register its callback into a queue and when the response is back the queue is popped and the values are then updated. This would take some time for you to build this mechanism or you may need to check how the jQuery Ajax Queue works.

This javascript setTimeout interacts with ajax requests in a really weird way

I'm writing this script so that it displays the status of an import script. It's supposed to call a function, that runs a http request, every X seconds.
function progres_import() {
//if(import_status != 'finalizat') {
alert("progres_import");
setTimeout(function() { return update_progres_import(); }, 2000);
setTimeout(function() { return update_progres_import(); }, 4000);
setTimeout(function() { return update_progres_import(); }, 6000);
setTimeout(function() { return update_progres_import(); }, 8000);
//setTimeout(function() { progres_import(); }, 400);
//}
//else {
//}
}
this is what i used to test the functionality. I put the comments in too just to show what I intend to ultimately do with it. I tried all the possible setTimeout calls, with quotes, without quotes, with and without the anonymous function.
var xmlhttp_import_progres;
function update_progres_import() {
xmlhttp_import_progres=GetXMLHttpObject();
if (xmlhttp_import_progres==null) {
alert ("Browser does not support HTTP Request (xmlhttp_import_progres)");
return;
}
var url="crm/ferestre/import_progres.php";
url=url+"?sid="+Math.random();
xmlhttp_import_progres.onreadystatechange=function() {
if (xmlhttp_import_progres.readyState == 4) {
progres_resp = xmlhttp_import_progres.responseText;
progres = progres_resp.split('_');
import_nrc = progres[0];
import_nrt = progres[1];
import_status = progres[2];
mesaj = 'Progres import: ' + import_nrc + ' / ' + import_nrt;
//document.getElementById("corp_import_mesaj").innerHTML = mesaj;
alert(progres_resp);
}
};
xmlhttp_import_progres.open("POST",url,true);
xmlhttp_import_progres.send(null);
}
this is the business end of the progres_import function.
what happens is i get the alert("progress_import") in the first function right as the import process starts, but the alert(progres_resp) in the second one starts popping up only after the import process is over (it still maintains the 2 second interval so in that sense the setTimeouts worked).
the php script in the ajax request just takes some session variables that the import script sets and prints them for the javascript to use (x imports of y total, z failed, stuff like this)
Any idea why it behaves like this?
xmlhttp_import_progres.readyState == 4) is only true at the end of the request. Hence, your alert dialogs pop up after finishing the request.
Furthermore, you can't expect your function to show alerts after a 2 second interval, because the server may or may not respond as fast.
A final note: If you want to have a periodical update function, use setInterval(function(){...}, 2000).
EDIT
Also, add var in this way: var xmlhttp_import_progres = GetXMLHttpObject();. Currently, you're globally defining the HTTP object, causing only one instance of the HTTP object to be accessible.
Here, can you try to edit just a little:
Please consider the above answer, but this code will make clear for you:
function progres_import() {
//if(import_status != 'finalizat') {
alert("progres_import");
setTimeout(function() { return update_progres_import(0); }, 2000);
setTimeout(function() { return update_progres_import(1); }, 4000);
setTimeout(function() { return update_progres_import(2); }, 6000);
setTimeout(function() { return update_progres_import(3); }, 8000);
//setTimeout(function() { progres_import(); }, 400);
//}
//else {
//}
}
AND
var xmlhttp_import_progres = [];
function update_progres_import(i) {
xmlhttp_import_progres[i]= GetXMLHttpObject();
if (xmlhttp_import_progres[i]==null) {
alert ("Browser does not support HTTP Request (xmlhttp_import_progres)");
return;
}
var url="crm/ferestre/import_progres.php";
url=url+"?sid="+Math.random();
xmlhttp_import_progres[i].onreadystatechange=function() {
if (xmlhttp_import_progres[i].readyState == 4) {
progres_resp = xmlhttp_import_progres[i].responseText;
progres = progres_resp.split('_');
import_nrc = progres[0];
import_nrt = progres[1];
import_status = progres[2];
mesaj = 'Progres import: ' + import_nrc + ' / ' + import_nrt;
//document.getElementById("corp_import_mesaj").innerHTML = mesaj;
alert(progres_resp);
}
};
xmlhttp_import_progres[i].open("POST",url,true);
xmlhttp_import_progres[i].send(null);
}

Need to delay javascript execution, but setTimeout is proving problematic

Thank you for taking the time to help me.
I am writing a game where an animated train icon moves along a given path to a destination, pausing at waypoints along the way. This is intended to give the impression of animation.
The game is coded in Facebook Javascript. I need to find a way to make the train icon pause for 1 second before moving on to the next waypoint. I hoped to find a function that would allow me to pause script execution for one second, but nothing like that seems to exist in JS. So I tried setTimeout, but my primary problem with this is twofold:
I need to pass an array into the callback function as an argument, and I can't figure out how to make setTimeout do this.
I finally succeeded in using setTimeout to execute my train animation code for 5 waypoints (I overcame the issue in 1 by using global variables). Unfortunately, it appears that all five calls to setTimeout got queued almost simultaneously, which resulted in waiting one second for the first setTimeout to fire, thenn they all fired at once ruining the illusion of train animation.
I've been battling this problem for six hours straight. It would be wonderful if someone could help me find a solution. Thanks!
Here's the code:
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;
}
Typically this would be done by creating an object (say called myTrain) that has all its own data and methods, then call a myTrain.run mehod that looks to see where the train is. If it's between two stations, it calls itself with setTimeout and say a 50ms delay. When it reaches a station, it calls itself in 1000ms, creating a 1 second pause at the station.
If you queue the setTimeouts all at once, you run the risk of them all being delayed by some other process, then all running at once.
Hey, bit of fun (careful of wrapping). Needed a bit of practice with good 'ole prototype inheritance:
<!-- 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> </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>
To pass arguments, this might help you:
setTimeout(function() {
(function(arg1, arg2) {
// you can use arg1 / arg2 here
})('something', 123);
}, 1000);
Or, if you use a defined function:
setTimeout(function() {
someFunction('something', 123);
}, 1000);
It basically starts a timeout; after one second the function is invoked with the specified arguments.
How about using OO principles to simplify the problem? Create an "object" Train which has the following methods:
//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
})
}
}
...
})
Here's the solution I finally came up with:
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);
}
}

Categories

Resources