neeraj bharti
neeraj bharti

Reputation: 361

How can I make jquery wait for one function to finish before executing another function?

function test(){
var distance=null;
       first();
       second();
       third();
alert(distance);//it shows null always because it take 2 second to complete.

}
 function first(tolat, tolon, fromlat,fromlon){

// calulating road distance between two points on the map using any other distance caluculating apis. 

distance=dis;  // update the value of distance but it takes 2 second to complete.

}
 function second(){}
 function third(){}

i have this type of situation in my code, now many time function three is called before first and second complete execution and distance value is not updated.

Upvotes: 18

Views: 70393

Answers (1)

anche
anche

Reputation: 2884

Make use of callbacks:

function first(tolat, tolon, fromlat, fromlon, callback) {
     if (typeof(callback) == 'function') {
        callback(distance);
     }
}

function second() { }
function third() { }

first("vartolat", "vartolon", "varfromlat", "varfromlon", function(distance) {
    alert(distance);
    second();
    third();
});

Upvotes: 17

Related Questions