I have 2 UDFs that need to be called sequentially.
Traditionally, Javascript will call function1() which once its commands are initiated, will then call function2(). Thing is, function1() has jQuery based animations, and I only want it to return and call function2() when it’s done. Since UDF’s don’t seem to have jQuery’s callbacks built into them, can anyone think of a way I can do this with my UDFs?
If you’re animating with jQuery you should be able to use its callbacks to call the second function.
e.g. something along the lines of:
function fn1( cb ) {
$("#something").fadeIn(500, function() {
cb.call(); // call the callback after the animation finishes
});
}
function fn2() {
//do something
}
fn1( fn2 );
Well, here’s the deal.
I have a function that is being executed, it gets to a point where it needs to call functionA() first and then functionB() after functionA() is done with the animations it runs.
function executingNow() {
// call function A, which runs jQuery animations
functionA();
// call function B, which needs to only run after functionA is done.
functionB();
}
As expected (but not wanted), Javascript executes functionA() and begins the animations. But then it immediately runs functionB() rather than wait for A’s animations to end.
Both functions take params, so ultimately I was hoping jQuery could just begin a series of functions (and their params) and as long as those params allow all their operations to complete before they return, it would work as needed.
Yup, I totally get where you’re going with this.
JavaScript is pretty flexible in that you can also pass functions as arguments to other functions. So for a normal scenario, we could do something like this:
function functionA( stringOne, stringTwo, callbackFunction ) {
var result = stringOne + stringTwo; //do something with stringOne and stringTwo
//when done:
callbackFunction( result );
}
function functionB( someResult ) {
//do something with someResult
}
function executingNow() {
functionA( "First", "Second", funcionB );
}
Of course, if functionA does some jQuery animations, those animations will be started, and then functionB would still be called before the animations finish.
This is why we would use the callback functionality in the jQuery animation functions to only execute code once they finish.
You would amend functionA to then only call the callbackFunction when the animation finishes:
function functionA( stringOne, stringTwo, callbackFunction ) {
var result = stringOne + stringTwo; //do something with stringOne and stringTwo
$("#something").html(result).fadeIn(500, function() {
callbackFunction( result ); //call this when the animation is finished
});
}