I'm developping a local (no server, no ajax) piece of code that does "heavy" computing and visual representations. My ever growing problem is thus : pieces of code will constantly be executed before preceding lines of code have finished! This is killing me and I've read, read and read about callbacks, promises, but unless I'm thick headed it doesn't seem to apply to my context and I can't wrap my head around how Javascript's flow of execution works.
If I call 3 functions from within a .js file loaded in the head of my html file like thus :
FirstFunction(lenghtOfDataset); // creates a complex array of arrays of objects (about 10,000 elements)
SecondFunction (Dataset); // renders a D3.js svg visualization based on the dataset (about 1,000 elements)
ThirdFunction (Dataset); // creates an html table by using jQuery .append (bad, I know) using the same dataset (around 10,000 elements)
Now, why, oh why does code in the third function is executed before the first function has even finished executing? (Of course, resulting in an "undefined" error)
Another example which drives me crazy goes like this :
$("#my-table").append("<thead><tr>");
for (i=FirstNumber; i<=LastNumber; i++) { // about 1000 elements
$("#my-table").append("<th>" + i + "</th>");
}
$("#my-table").append("</tr></thead>");
Again, why, oh why does the closing "</tr></thead>
" get inserted before the for loop is even finished?!
EDIT : OK this example has invalid code, thanks to mplungjan for providing a solution, but this is not the main issue. Consider this code then :
$("#working-overlay").css("display", "block");
for (var i = 1; i <= 10000; i++) {
Number[i] = {};
Number[i].value = i;
Number[i].divisors = DivisorsOf(i); // I have a function that calculates divisors
Number[i].factors = FactorsOf(i); //// I have a function that calculates factors
}
$("#working-overlay").css("display", "none");
The working-overlay will get display:none before computation is finished. How to go about not behaving that way? I don't really care about the overlay here, it's an example, but I do care that the next computation in line will refer to an undefined value because the for loop isn't really finished when the next line of code is executed.
Please note that I'm not looking for a copy-and-paste solution nor a workaround in the setTimeout style (works inconsistently, anyway), but I want to understand why it behaves like so: why does Javascript code execution flows, weirdly, ahead of itself?