15

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
    Literally one();two();, but I think what you actually mean is wait for the timer callback to execute before calling two(), right? Commented Apr 3, 2017 at 14:55
  • Yes @spender i mean wait for the timer. Commented Apr 3, 2017 at 14:58

1 Answer 1

28

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)

Sign up to request clarification or add additional context in comments.

5 Comments

There is no wait between functions one and two in this example. You could add one, but I think callbacks and promises are a little complex for beginners and are a bit over-the top and unnecessary for the simple task at hand. Not to mention that this code simply looks more confusing to beginners.
Thanx @KevBot, this is a perfect example for promise. I couldn't find anywhere so an easy example.
@Feathercrown, there is, it waits 3 seconds to console.log, and then immediately calls function two. And the only difference in "complexity" of yours vs mine (for callbacks) is that I formatted my code to multiple lines.
@AdamJungen, Great! I'm glad that the Promises example helped and provided more context for understanding promises.
Hi! I know this is an old question, but in the accepted answer, can anyone tell me how this would work if function one had an additional parameter, i.e. function one (callback, parameter1)? How would one(two) need to be re-written?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.