Skip to content Skip to sidebar Skip to footer

Forcing One Javascript Function To Wait To Run Until The First Has Finished

Afternoon all, I am running into an issue where i need to run one function, then after that is finished, run the next, and do this for four functions, i have been at this for a whi

Solution 1:

You want to chain asynchronous function calls.

Use jQuery's deffered.then method :

ajax functions, like $.ajax(), $.post(), $.get(), return a Deferred object.

You can use this in your case :

functioncontentajax(){
    // add the return instruction to return the Deferred objectreturn $.post("templates/content.php", {... });
}

functionfooterajax(){
    //same herereturn $.post("templates/footer.php", { ... }); 
}

// chain the deferred calls :contentajax()
   .then( footerajax() )
   .then( csschanges() )

If you also want to wait for the loading of the images to complete, you can still use this Deferred abstraction by wrapping the loading mechanism inside a single Promise. I googled around and found this gist (due credit should be given to the author : Adam Luikart).

Solution 2:

Try to use callback function.

  • Instead of using .css try using .animation({'':''},200,function(){"........another function here......"})
  • Same with fadeOut as .fadeOut(200,function(){".....another function here........."})

So at the end you will only call contentajax().

Hope that helps.

Solution 3:

By default your ajax calls are async. You can't guarantee the order of returns async. It sounds like you want execution in synchronous order. Either use async: false in your ajax calls, or use each next function as a success callback to the current one and don't loop through them in preload.

        success: function(data, textStatus, jqXHR)
        {
                successCallback(successCallbackArgs);
        }

Post a Comment for "Forcing One Javascript Function To Wait To Run Until The First Has Finished"