As we code in JavaScript, we expect our commands to be executed in the same order we write them. In a lot of cases, that works great. However, an issue arises when we start using statements that take a certain period of time - for example, visual effects. One statement might be started before the previous one finishes.
In such cases, the jQuery callback function comes to play. It allows a developer to make sure one code line is finished before the other one begins. By forming a queue of events, jQuery callback prevents effects from overlapping and causing issues.
jQuery Callback: Main Tips
- JavaScript statements are run one line after another. However, effects may start running before another effect is finished. That can cause errors and unexpected behaviors.
- jQuery callback functions stops this from happening by forming a queue. It prevents another effect from being executed before the current one is complete.
Explanation and Examples
Typically, JavaScript runs statements one after another. In some cases, this might mean an effect start being executed before the previous one is done. To prevent this, jQuery callback functions are used. As you apply them to particular methods, they are only run once a specified effect is complete.
To better illustrate jQuery callback functions, let's look at two examples of similar code.
The example below shows a code which has a button. Upon being clicked, it will execute the .fadeOut() method on a paragraph and display an alert message saying that the paragraph has faded out. This will happen before the animation is complete:
$("button").click(() => {
$("p").hide(500);
alert("The paragraph is now gone");
});
However, the same example can be written with the alert being a part of the .fadeOut() method's callback function jQuery offers. That would make it so the alert does not pop up until the animation has been completed:
$("button").click(() => {
$("p").hide("slow", () => {
alert("Congratulations it works");
});
});
jQuery Callback: Summary
- In JavaScript, statement lines are executed one by one. It might cause problems at times, as a certain effect might start running before the previous one finishes.
- To prevent that, callback function jQuery comes in handy. It creates a queue of effects so they are run in a row.