In, for example, the
article on Quicksort, on this site, this technique is
used to guarantee that the charting function, littleChart, is available, before it is
called. If it isn't available, the in-line function uses setTimeOut to
call itself again later (I chose after one second, you could pick any time interval
you like). Its code looks like this:
<SCRIPT Language="JavaScript">
function drawCharts()
{
if (document.isChartJSLoaded==null)
{
//alert("charts not loaded");
setTimeout("drawCharts()",1000);
return;
}
//
//... do things that rely on the functions defined by performanceChart.js
// here... only at the point where we KNOW it has loaded
//
}
</SCRIPT;>
At the top of the same document (but it could be anywhere, and even if you put it
at the top of the document the javascript include mightn't finish until after the
rest of the document has been read!), there is the usual javascript
call-in. That doesn't change:
<SCRIPT Language="JavaScript" SRC="../../library/performanceChart.js">
</SCRIPT;>
I won't quote the source code of performanceChart.js - it merely renders the little
graphs in the Quicksort article. The only line that is relevant is the very last one:
document.isChartJSLoaded = true;
So, to guarantee that you don't try to do anything that needs something that mightn't
be defined, you can define something else only later and
then exploit the fact that it won't be defined if the thing you need isn't.
If you simply have to do that "anything", as soon as possible,
you can whip up a setTimeOut "loop" (but not a busy polling loop,
which will hang your browser!) that waits until the "something else" has
become defined.
In other words, you use the race problem itself to solve the race problem.
Life's like that. Often the problem is its own solution. Instead of fighting
against it, you can make it fight on your side. But it can be difficult to think of
that, when you're struggling to meet a deadline!