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 function executed");
}

How can i let second function waits till first function executed? What is the easiest way for a beginner? Thanx

2

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)
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest