Home > UI/UX Development > JavaScript > Callbacks in jQuery

Callbacks in jQuery

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
  • code sample 2: with callback

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
This Article is TAGGED in . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">