Search code examples
jqueryeventsfunctionparallel-processingready

jQuery do something when an own function is ready


I'd like to priorize my functions.

$(document).ready(function(){
drawMap();
on showLinks() ready do drawChart();
});

How can i do this with jQuery?

Thanks, Répás


Solution

  • As Gary already mentioned in his answer, you'd only want to do this if you are dealing with asynchronous execution.

    You might want to take a look on deferreds that was introduced in jQuery 1.5.

    In your case it would look something like this:

    $(function(){
        drawMap();
        $.when(showLinks())
            .then(drawChart);
    });
    

    To make the above work you must make sure that the showLinks function return a promise and that it triggers resolve once it's done executing.

    function showLinks(){
        var dfd = $.Deferred();
    
        // Add your asynchronous code here
        setTimeout(function(){
            console.log("Links shown!");
            dfd.resolve(); 
        }, 1000);
    
        return dfd.promise();
    }
    

    Check test case on jsFiddle