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.
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 .
const yourFunction = async () => { await delay(5000); console. log("Waited 5s"); await delay(5000); console. log("Waited an additional 5s"); };
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.
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].
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With