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
If we have three synchronous functions, we can execute them asynchronously using the setTimeout function. setTimeout(doSomething, 10); setTimeout(doSomethingElse, 10); setTimeout(doSomethingUsefulThisTime, 10);
function a() { // first function code here $(document). trigger('function_a_complete'); } function b() { // second function code here } $(document). bind('function_a_complete', b); Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.
Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions. Thank you! Hi Suraj, Below code is not working.
You can't 'merge' functions as you describe them there, but what you can do is have one function be redefined to call both itself and a new function (before or after the original). var xyz = function(){ console. log('xyz'); }; var abc = function(){ console.
There are a couple of ways you could approach this, the two most common ways would be using a callback, or using Promises.
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)
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)
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