forcing one javascript function to wait to run until the first has finished

一曲冷凌霜 提交于 2019-12-02 11:30:23

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 :

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

function footerajax(){
    //same here
    return $.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).

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.

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);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!