Kevmon Kevmon - 3 months ago 19
Javascript Question

jQuery with Callback and Complete

So I want to use a callback function within

.fadeOut()
after it complete's the animation. I can do this successfully using the following, no problem. Works just like I want (The HTML and CSS are just a single black square div)

function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}

function OtherThing() {
console.log("hello");
}

fadeOutThing(5000, OtherThing);


What I really want is for that callback function have its own argument, which could be another callback function, like the following. The problem is that when I do this, the log will display before the animation is complete: Here's the fiddle

function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}

function OtherThing(stuff) {
console.log("hello" + stuff); //This displays too soon!
}

fadeOutThing(5000, OtherThing(' stuffsss'));


Why is this happening? What am I not understanding?

Answer

The issue is because you call OtherThing() immediately on load of the page. This means you're giving the result of the OtherThing() function as the callback parameter, not the reference to the function.

To do what you require you can provide an anonymous function to the callback which wraps your OtherThing() call:

fadeOutThing(5000, function() {
    OtherThing(' stuffsss'));
});
Comments