0

How can I implement this code to run in correct order (A and B) without change the setTime using only callback?

function a() {
  setTimeout(function () {
    console.log('a');
  },1000);
}

function b() {
  console.log('b');
}

function c() {
  a();
  b();
}

c();

When run the c(), I need to run a() and b() in synchronous order, that's:

  1. wait a sec;
  2. run a() function...
  3. ... and then, run b() function
2
  • 1
    Who do you mean by "without change the setTime using only callback?"? Commented Mar 1, 2017 at 2:41
  • 2
    That's sequential, not "synchronous". setTimeout is always asynchronous. Commented Mar 1, 2017 at 2:43

2 Answers 2

3

You mentioned using a callback - simply add an argument to a() that is a callback function that you will call after doing the console.log(a), then when you call a() pass a reference to b:

function a(callback) {
  setTimeout(function () {
    console.log('a');
    if (typeof callback === 'function')
      callback();
  },1000);
}

function b() {
  console.log('b');
}

a(b);   // note: no parentheses after b, i.e., a(b), *not* a(b())
a();    // note: a() still works without any argument

The test within a() to check that callback actually is a reference to a function means you can choose not to pass a callback and a() will still work.

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

Comments

1

The asynchronous operation (what's being done in setTimeout()) would need a callback to invoke when it's finished. Provide that callback to a():

function a(callback) {
  setTimeout(function () {
    console.log('a');
    if (typeof callback === "function") { 
      callback();
    }
  },1000);
}

Then pass a reference to b for that callback:

function c() {
  a(b);
}

1 Comment

Great David. Thanks so much!

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.