简体   繁体   中英

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 while trying to find the correct syntax to layout my function calls in and cant seem to find anything to address this specific scenario.

html:

<div id = "putcontenthereafterajax">
</div><!--end putcontenthereafterajax-->

<div id = "putfooterhereafterajax">
</div<!--end putfooterhereafterajax-->

jquery:

$(window).load(function() { 


function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        //alert("I cached "+this+"");
    });
    $('#progressbarinner').css("width","200px");//change the width of the inner progress bar div
}

function changecss(){
    $('.hidetillcache').css("visibility","visible");//make the page visible
    $('#loadingscreen').fadeOut("slow");
}

function contentajax(){
    $.post("templates/content.php",
    {
        whatamidoing:"imgettingthecontent"
    },
    function(data){
        $('#putcontenthereafterajax').after(''+data+'');
        $('#progressbarinner').css("width","400px");//change the width of the inner progress bar div
    });
}

function footerajax(){
    $.post("templates/footer.php",
    {
        whatamidoing:"imgettingthefooter"
    },
    function(data){
        $('#putfooterhereafterajax').after(''+data+'');
        $('#progressbarinner').css("width","500px");//change the width of the inner progress bar div
    }); 
}

preload([
    'images/careers.jpg',
    'images/careers.png',
    'images/contact.jpg',
    'images/facebook.png',
    'images/footer.png',
    'images/footerblack.png',
    'images/footergrey.png',
    'images/home.jpg',
    'images/media.jpg',
    'images/media.png',
    'images/myitv3.jpg',
    'images/newindex.jpg',
    'images/newindex.png',
    'images/services.jpg',
    'images/twitter.png'
], contentajax(), footerajax(), csschanges());

});

basically i have a loading bar that fills up a bit after each function is finished which in turn requries each function to be ran one after another in the correct order, all the functions do work, the caching and the ajax and even the css changes work. however i cant seem to find a way to force them in the right order and to wait to run until the previous is finished in order to compliment the loading bar. Anyone have any ideas?

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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM