I've been programming for a few years but I'm new to JavaScript. I'm trying to create a hacky version of a standard thread 'notify' function. I'm running a series of ajax data requests that each take about 200 milliseconds to execute, and I need to wait for them ALL to finish before performing an action (drawing a graph).
My solution was to have each thread increment a global variable when it finished. I then created a timer using setTimeout to check every 100 milliseconds to see if all threads had updated the variable, and if they had, to perform the action.
Despite being a bit hacky, this worked.
Fast-forward a few weeks into the future and my program is growing, and we now need to be able to have several graphs on the same page, each of which manages its data independently using the aforementioned ajax requests, as well as having several different pages that use the graphs. So I extract the graphing code into a module with require.js, and define a class that performs the graphing to isolate each graph from the others, but suddenly setInterval doesn't work. I do some Googling and find the following article, which I sort of understand...
So anyway it seems that 'this' becomes the window for some strange reason when setInterval is used, and therefore it can't see my methods.
Anyway, I tried creating a var inst to contain 'this' explicitly, which seemed to help, but for some reason it doesn't like passing 'inst' as an argument in the recursive call. The error message from the Firebug console is this:
missing ] after element list [Break On This Error]
}(9.9, [object Object]))
Here's a sample from my code:
var inst = this;
// some code... then in a function...
function (){
inst.waitUntil(10, inst);
}
inst.waitUntil = function(how_many_seconds, inst){
if (how_many_seconds < 0){
alert("Script timed out.");
return;
} else {
if (inst.allSchoolsLoaded()){
setTimeout("("+inst.draw+"("+inst.after+"))", 100);
} else {
var argString = "("+inst.waitUntil+"("+(how_many_seconds-0.1)+", "+inst+"))";
//alert(argString);
setTimeout(argString, 100);
}
}
}
You can assume all the variables mentioned are defined earlier in the class.
I'm at my wits end here, any help would be really appreciated. If anyone can suggest a better solution for the threading issue that avoids setInterval entirely, that would be awesome, otherwise if you can propose a way to get setInterval to work or an alternative function that would be great too.
jQuery is available, and I don't mind installing other tools if they will help.
Many thanks in advance,
Alex