Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way of executing 2 functions one after another in Javascript

Tags:

javascript

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

like image 915
Adam Jungen Avatar asked Apr 03 '17 14:04

Adam Jungen


People also ask

How should I call 3 functions in order to execute them one after the other?

If we have three synchronous functions, we can execute them asynchronously using the setTimeout function. setTimeout(doSomething, 10); setTimeout(doSomethingElse, 10); setTimeout(doSomethingUsefulThisTime, 10);

How do you execute a function after another JavaScript?

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.

Can we run two functions simultaneously in JavaScript?

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.

How do you combine two JavaScript functions?

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.


1 Answers

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)
like image 184
KevBot Avatar answered Oct 13 '22 01:10

KevBot