How To Wait For A Function To Finish In Jquery

In this blog post, we’ll explore how to wait for a function to finish executing in jQuery before moving on to
the next task. This can be particularly useful in scenarios where you need to run animations, fetch data from
the server, or perform other asynchronous tasks.

Using Callback Functions

One of the simplest ways to wait for a function to complete is by using callback functions.
Callbacks are functions that are passed as arguments to other functions and are executed once the parent
function has completed its task. Let’s take a look at an example:

Example with callback

Suppose we have the following HTML structure:

<div id="box">
  <h2>Hello World!</h2>
</div>
    

We want to hide the “Hello World!” text, wait for 3 seconds, and then show it again. We can achieve this using callbacks like so:

function hideElement(callback) {
  $("#box").fadeOut("slow", callback);
}

function showElement() {
  setTimeout(function() {
    $("#box").fadeIn("slow");
  }, 3000);
}

$(document).ready(function() {
  hideElement(showElement);
});
    

In this example, we pass the showElement function as a callback to the
hideElement function. When the fadeOut animation in
hideElement is complete, the showElement function is called, which then
waits for 3 seconds and shows the “#box” element again.

Using Promises

Another method for waiting for a function to complete is by using promises. Promises are a
more modern and powerful way of dealing with asynchronous tasks. They represent the eventual completion (or
failure) of an asynchronous operation and its resulting value.

Example with Promises

Let’s refactor the previous example using promises:

function hideElement() {
  return new Promise(function(resolve) {
    $("#box").fadeOut("slow", resolve);
  });
}

function showElement() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      $("#box").fadeIn("slow", resolve);
    }, 3000);
  });
}

$(document).ready(function() {
  hideElement()
    .then(showElement)
    .catch(function(error) {
      console.log("An error occurred:", error);
    });
});
    

In this example, both hideElement and showElement return promises. The
then method is used to chain the promises, ensuring that the showElement
function is executed only after the hideElement function has completed. The
catch method is used to handle any errors that might occur during the execution of the
functions.

Conclusion

In this blog post, we’ve explored two methods for waiting for a function to finish in jQuery: using callback
functions and using promises. Both methods have their advantages and can be used according to your specific
needs and coding style preferences.