Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 438
neeraj bharti Avatar asked Oct 23 '12 12:10

neeraj bharti


People also ask

How do you make a function wait for another function to finish?

Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .

How do you make a function wait before executing?

const yourFunction = async () => { await delay(5000); console. log("Waited 5s"); await delay(5000); console. log("Waited an additional 5s"); };

How do you make a function wait for a second?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.

How do I call a function after another function ends in jquery?

You should use a callback parameter: function Typer(callback) { var srcText = 'EXAMPLE '; var i = 0; var result = srcText[i]; var interval = setInterval(function() { if(i == srcText. length - 1) { clearInterval(interval); callback(); return; } i++; result += srcText[i].


1 Answers

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();
});
like image 110
Angelo A Avatar answered Sep 23 '22 09:09

Angelo A