JavaScript executes code line by line, moving to the next line immediately.
Because jQuery animations take time to finish, the next line of code can execute while the animation is still running.
This can create massive errors and unpredictable behavior on your website.
To prevent these errors, jQuery provides Callback functions.
A Callback function is executed strictly after the current animation is 100% complete.
You place the callback as a parameter inside the effect method.
Here is how to properly trigger an alert only after the element has completely hidden itself.
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
If you don't use a callback, the alert will pop up immediately.
The paragraph will still be hiding in the background while the alert is blocking the screen.
$("button").click(function(){
$("p").hide("slow");
alert("The paragraph is now hidden"); // This triggers too early!
});
Callbacks are essential for chaining complex logic together.
If you want to hide an element, delete it from the database, and show a success message, you must wait for the hiding to finish first.
Always use a callback when executing code that depends on the result of an animation.
When is a jQuery callback function executed?