I have 3 different jQuery functions like:
function step1() {
...
}
function step2() {
...
}
function step3() {
...
}
and if I call them like this:
step1();
step2();
step3();
they will be all executed in the same time. How can I call them one by one so step2(); is called after step1(); is finished and step3(); is called after step2(); is finished.
// MORE INFO
Step1() is executing a json and appends details to html, Step2() is executing another json and appends info in the divs created by Step1() and Step3() simply hides a loading animation.
// THE FUNCTIONS
As requested by some users, here are the functions:
jQuery.noConflict();
jQuery(document).ready(function($) {
var cardType = $.cookie('cardType');
var categoryID = $.cookie('categoryID');
function step1() {
$.getJSON('http://domain.com/benefits/active/all.json', function(data) {
$.each(data, function(i,item){
if (item.benefit_type_id == categoryID) {
content = '<li><a class="showDetails" data-offer-description="' + item.description + '" data-offer-period="' + item.begin_date + ' - ' + item.end_date + '"><div class="company" title="' + item.business_id + '"></div><div class="shortdescription">' + item.name + '</div></a></li>';
$(content).appendTo("#thelist");
}
});
step2();
});
} // function step1();
function step2() {
$('.company').each(function(i, item) {
var tempTitle = item.title;
$.getJSON('http://domain.com/businesses/from_list/' + tempTitle + '.json', function(data2) {
$.each(data2, function(i,item){
content = '<span>' + item.name + '</span>';
$(content).appendTo("div[title='" + tempTitle + "']");
});
step3();
});
});
} // function step2();
function step3() {
loaded();
$('#loading').delay(1000).fadeOut('slow', function() {
// Animation complete.
});
} // function step3();
step1();
});
Not knowing what you are executing in each function, I’m assuming none of them executes an asynchronous call themselves, i.e: ajax request and so on.
Should you have additional asynchronous calls occur in each function the below would not apply as is.
One option would be to use call one from the other similar to this:
or you can use callbacks in the function signature, similar to this:
Or using jQuery deferred might work, similar to this:
I’m not 100% sure on the deferred solution using
.when().The code above seems to work (DEMO) using
when()but asFelixKingmentioned in the comments if you update the methods to return a deferred promise you can do this:DEMO – Using a deferred promise
Sample-Code from DEMO: