views:

116

answers:

3

I am using a function supplied by a third party library. This function takes a callback function as a parameter, but I would like to wait for this callback to be called before continuing. Is there a standard / accepted way to do this?

+1  A: 

if you can write something on that third party callback, then do something like,

var wait = true;


// in the callback, provide something like,
... :function(){
   wait = !wait;
}


// somewhere else
var time = setInterval(function(){
   if (!wait){
   clearInterval(time);
   // I will continue my job now...
   }
},1000)
Reigel
You're not waiting fot the callback to be called. The code inside your condition will most likely never run.
Savageman
good point... please see edit...
Reigel
+1  A: 

I am not sure if this is a possible solution for you but you can achieve the desired result by breaking your code into 2 functions. Suppose this is what you intend to do:

Basically this is your original function:

function origFunc() {

    codeBeforeThirdPartyFunc();
    ThirdPartyFunc(oldCallBackFunc);
    Wait();
    codeAfterCallBackFunc();
}

You can modify the code flow with something like:

function newFunc() {
    codeBeforeThirdPartyFunc();
    ThirdPartyFunc(newCallBackFunc);
}
function newCallBackFunc() {
  oldCallBackFunc();
  codeAfterCallBackFunc();
}

This will eliminate the wait loop. And as far as I know, busy waiting doesn't work in IE (because ? God only knows)..

Sharad
A: 

I don't know if Sharad's solution would work in all cases (for instance if you function calls are so far chained that you have to pass data as variables instead of parameters). Same problem with global variables. JavaScript just doesn't have a "wait" ability.

Although I had a similar problem and with jQuery, I ended up with a MacGyver type solution that gives you tons of control on when javascript functions execute. I just posted it here as an answer to my own question (but I it's an answer that's not checked - look for my username Emile): http://stackoverflow.com/questions/3531080/how-to-get-a-variable-returned-across-multiple-functions-javascript-jquery

Emile