1

So I was doing some practice about callback function and I wanted to try it out in my own was and use it with a setTimeout Method and to my surprise, it didn't work as expected.. Pls what am i doing wrong here.

function first(number, callback) {
  setTimeout(function() {
    console.log(number);
  }, 5);
  callback();
}

function second() {
  console.log(2);
}

first(1, second);

2
  • 1
    What did you expect? Commented Aug 20, 2018 at 15:39
  • 1
    4ms is the minimum time for settimeout Commented Aug 20, 2018 at 15:43

2 Answers 2

2

You're executing setTimeout and callback at the same time. Because JavaScript is single-threaded, it doesn't wait for setTimeout to complete before executing the next statement.

That's why, 2 prints immediately, and then 1 prints after a delay of 5 milliseconds.

If you want to print 1 first, then you need to call the callback function in the callback of setTimeout. This ensures that the console.log(number) executes prior to calling the callback (which prints 2).

function first(number, callback) {
  setTimeout(function() {
    console.log(number);
    callback();
  }, 5);
}

function second() {
  console.log(2);
}

first(1, second);

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

Comments

0

As 31piy already said, setTimeout() and callback() are being executed at the same time. Your code first schedules a function execution at 5ms from now, and then immediately runs another function that logs 2 to the console.

You can achieve the expected result in a couple of similar ways, I'll show one:

function first(number,callback) {
  setTimeout(function() {
    callback();
  }, 5);
  
  console.log(number);
}

function second() {
  console.log(2);
}

first(1, second);

//Here, you immediately print the number 1 and schedule the number 2.

Comments

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.