Efficient Way of Executing 2 Functions One After Another in Javascript
I Have Two Functions Function One() { setTimeout(function(){ Console. Log("First Function Executed"); }, 3000); } Function Two() { Console. Log("Second...
I have two functions
function one() {
setTimeout(function(){ console.log("first function executed"); }, 3000);
}
function two() {
console.log("second function executed");
}
How can i let second function waits till first function executed? What is the easiest way for a beginner? Thanx
1 Answer
There are a couple of ways you could approach this, the two most common ways would be using a callback, or using Promises.
Using Callbacks
You would add a callback argument to the first function, and then pass in function two as the callback:
function one(callback) {
setTimeout(function() {
console.log("first function executed");
callback();
}, 3000);
}
function two() {
console.log("second function executed");
}
one(two)
Using Promises:
Promises allow you to chain different actions together that are dependant on ordering. However, you may need to add polyfills to support older browsers:
function one() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("first function executed");
resolve();
}, 3000);
})
}
function two() {
console.log("second function executed");
}
one().then(two)