Busy Waiting in Javascript
Posted on 06/06/2008 @ 01:25PMSometimes, particularly in sites that use large amounts of AJAX, we developers run into race conditions. Maybe the flash movie has to be loaded before a piece of Javascript executes. Or one piece of Javascript must run before another. And so on.
Busy waiting is one way of resolving a race condition. If we need Javascript function A() to finish before running B(), we first have A() set some sort of flag to let us know its done.
var A_FINISHED = false;
function A()
{
// ...an AJAX call/async code...
A_FINISHED = true;
}
function B()
{
// ...can't run until A() is done...
}
/*-----------------------*/
// Now run the actual code
A();
waitFor({
condition: function()
{
return A_Finished === true;
},
callback: function()
{
B();
}
});
While A() runs asynchronously, the waitFor() function I've written will check every 100 milliseconds to see if the A_FINISHED flag has been set. Here's the function itself:
var waitFor = function( params )
{
var condition = params.condition;
var callback = params.callback;
var interval = params.interval || 100;
var maxTries = params.maxTries || 5;
var currentTry = params._currentTry || 0; // private
// If condition passes, run the code
if ( condition() === true )
return callback();
// Limit the # of attempts
if ( currentTry < maxTries )
{
// Increment the attempt #
params._currentTry = currentTry+1;
// Create the recursive call
var f = function() { return waitFor( params ); }
// Wait for one interval and execute
setTimeout( f, interval );
}
else
{
// alert( 'Maximum tries used for waitFor()...quitting' );
}
};