This post was most recently updated on August 2nd, 2024
Hello everyone, in this post we will discuss about following points on JavaScript Callbacks
- What is Callback in jQuery?
- Pros of callback in jQuery
What is Callback in jQuery?
A callback is a function called at the completion of a current effect. This prevents any blocking, and allows other code to be run in the meantime.
A callback function also known as a higher-order function. We know that in JavaScript, statements are executed line by line. But since jQuery effect takes some time to finish the job, next line code may execute while the previous effect is still running. To prevent this from happening jQuery provides a callback function for each effect method.
Typical syntax: $(selector).show(speed,callback);
Consider following code sample
- code sample 1: without callback
1234$("button").click(function(){$(".userContent").hide(5000);alert("User information is now hidden");});
- code sample 2: with callback
12345$("button").click(function(){$(".userContent").hide("slow", function(){alert("User information is now hidden");});});
Code sample 1 has no callback parameter that’s why alert box will be pop up before the hide effect is completed.
Code sample 2 has a callback parameter that’s why alert box will be pop up after the hide effect is completed.
Pros of callback in jQuery
- If you execute a long-running operation within a single-threaded event loop, so callback is better option. A callback function will execute last if placed last in the function.
- Callback prevents blocking, and allows other code to be run in the meantime.
- Better choice over setTimeout() and setInterval() events