So I have a sections of code that is going to be running at least 10 seconds (It is going through around 14000000(14 states* 1000000 for numTimes) iterations of doing stuff. I need to make sure the browser doesn't stop responding part way through as it currently is. I looked at the question How to stop intense Javascript loop from freezing the browser
However, I can't use a setTimeout because of the function needing a reference to this. I did try to make a temporary variable that stores this and pass that to a setTimeout, but it wouldn't recognize my functions and variables of the new variable = this. (This is an object that stores tables, arrays, an array of objects, and some data) Any ideas?
Agent.prototype.performActions = function(numTimes)
{
/* perform a random action for every state
numTimes.
*/
var len = this.states.length; // get the amount of states
var count = 0;
for(var i = 0; i < len; i++) // loop over every state
{
var state = this.states[i]; // the current state so we don't lose time accessing it again
if(state.terminal != 1) // not a terminal state
{
for(var j=0; j < numTimes; j++) // the num of times to do a random action perstate
{
var that = this;
setTimeout(function(){
var acts = state.actions.length; // the number of actions
var randAct = Math.floor((Math.random() * acts)); // random actions between 0 and 3
var randProb = Math.random(); // number between 0 and 1 to figure out which state we end up in
var locs = that.states[i].locations[randAct]; // saves time
var tote=0;
var alen = that.states[i].actions[randAct].length
for(var k=0; k < alen; k++) //num of state checking
{
tote += that.states[i].actions[randAct][k];
if(randProb <= tote)
{
// we found where we landed
that.states[i].actCounts[randAct] += 1;
var numPos = locs.length;
for(var l=0; l < numPos; l++) // get the num of possible states
{
if(locs[l].stateNum == k)
{
count += 1;
that.states[i].locations[randAct][l].times += 1;
break;
}
}
break;
}
}
}, 1);
}
}
}
var inner = document.getElementById("run").innerHTML;
document.getElementById("run").innerHTML = inner+"<p>Finished with performActions num actions = " + count + "</p>";
} for(var l=0; l < numPos; l++) // get the num of possible states
{
if(locs[l].stateNum == k)
{
count += 1;
that.states[i].locations[randAct][l].times += 1;
break;
}
}
break;
}
}
}, 1);
}
}
}
var inner = document.getElementById("run").innerHTML;
document.getElementById("run").innerHTML = inner+"<p>Finished with performActions num actions = " + count + "</p>";
}