Omolayo Victor
Omolayo Victor

Reputation: 29

JavaScript CallBack Function ..ish issue

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

Upvotes: 1

Views: 47

Answers (2)

Sacha
Sacha

Reputation: 861

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.

Upvotes: 0

31piy
31piy

Reputation: 23859

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

Upvotes: 2

Related Questions