betzebube1000
betzebube1000

Reputation: 91

Javascript, simple callback example not working as expected

First, thanks alot for anybody who will have a look at my question. It is totally basic but I just don`t get it. I have looked through all tutorials, but asynchronous callbacks drive me crazy. Thank you so much for helping out, greetings from Germany :)

If somebody could tell me why below code does not log into the console as expected. Expected means, callback is called after the Timeout function has completed. Instead, my console logs the callback first? What am I still getting wrong here?

function doHomework(subject, callback) {
  setTimeout(function () {
   console.log(`Starting my ${subject} homework.`);
  }, 10);
  callback();
}

doHomework('math', function() {
  console.log('Finished my homework');
});

Upvotes: 0

Views: 94

Answers (2)

Delvian
Delvian

Reputation: 185

The problem is that you execute the callback outside of your setTimeout function. Javascript executes code asynchronously, meaning that it does not wait until the previous code is "finished" before it continues to the next line.

Hence, when you call doHomework, it will start the timer, and immediately continue to the next line of code, which is the callback. Then, when the 10ms is over, the code inside the timeout is executed. In order to get the desired result, you will have to place the callback execution inside the setTimeout function, like so:

function doHomework(subject, callback) {
   setTimeout(function () {
      console.log(`Starting my ${subject} homework.`);
      callback();
   }, 10);
}

Upvotes: 1

Aliaksandr Sushkevich
Aliaksandr Sushkevich

Reputation: 12364

You need to put the call of a callback function inside your setTimeout

function doHomework(subject, callback) {
  setTimeout(function () {
   console.log(`Starting my ${subject} homework.`);
   callback();
  }, 10);
}

Upvotes: 1

Related Questions