jQuery Callback Function

jQuery is based on JavaScript. JavaScript statements are run one line after another, however, effects may be run despite another effect may not be finished yet, causing errors and unexpected behaviors. Similarly, the code in jQuery will also execute sequentially. When we use animation in jQuery the execution order of code will be changed. In other words it will execute the next line of the code without waiting to complete the first line. Callback functions prevent this from happening as they form a queue, preventing another effect from being executed before the current one is complete. Then lend structure and timing to our code.
var div = $("div"); div.animate({height: 600,width: 800}, 2000,function(){ alert("Animation Finished !!"); });
In the above code, you can see the callback function itself is defined in the third argument passed to the function call. That code has another alert message to tell you that the callback code has now executed.
run this source code Browser View
jQuery Callback()
Full Source
<html> <head> <title>jQuery Callback example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btnStart").click(function(){ var div = $("div"); div.animate({height: 600,width: 800}, 2000,function(){ alert("Animation Finished !!"); }); }); }); </script> </head> <body> <button id="btnStart">Start Animation</button> <div style="height:150;width:200;background:green;position:absolute;"> jQuery Callback() </div> </body> </html>
The example below has no callback parameter , and the alert box will be displayed before the animation effect is completed:
$("#btnStart").click(function(){ var div = $("div"); div.animate({height: 600,width: 800}, 2000); alert("Animation Finished !!"); });
run this source code Browser View
jQuery Callback()
Full Source
<html> <head> <title>jQuery Callback example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btnStart").click(function(){ var div = $("div"); div.animate({height: 600,width: 800}, 2000); alert("Animation Finished !!"); }); }); </script> </head> <body> <button id="btnStart">Start Animation</button> <div style="height:150;width:200;background:green;position:absolute;"> jQuery Callback() </div> </body> </html>