5

I'm not getting the desired results with this below callback. I'm trying to write a simple callback which executes after setTimeout is done, however I'm seeing the callback function execution first followed by the actual function.

What I'm missing here? to get the results as below.

doing my homework Maths
finished my homework

Here is the code I'm trying to run.

function doHomeWork(subject, callback){
setTimeout(function(){console.log("doing my homework:", subject)},500)
callback();
}
doHomeWork("Maths", function(){console.log("finished my homework");});
asked Mar 23, 2019 at 14:38
2
  • 4
    You need to place the callback() call inside the timeout! Put it after the console.log call. Currently you are starting the timer with setTimeout(), then immediately calling the callback(). Commented Mar 23, 2019 at 14:40
  • ^^ using proper indentation and line breaks makes the mistake easier to spot: pastebin.com/WWQHSPN9 (Voting to close as typo/non-repro/not-useful-to-others-in-future) Commented Mar 23, 2019 at 14:41

4 Answers 4

5

When you call setTimeout() a browser callback is registered. It does not mean subsequent statements will also get executed later. They will execute immediately after calling function setTimeout(). Only the function parameter you have passed will be called by setTimeout() when the timeout occurs. So, if the callback needs to be executed after setTimeout() parameterized function. It is better to move that call inside setTimeout() function parameter. So, the code will look like

setTimeout(function() {
 //Your stuff
 callback();
}, 500);
answered Mar 23, 2019 at 14:44
Sign up to request clarification or add additional context in comments.

3 Comments

You can probably assume that the console.log() in his timeout function is supposed to go before your setTimeout() call.
"When you call setTimeout() a separate thread starts" No, that's not correct at all. The browser adds a timer to its list of timers. The browser queues a task in the thread's job queue and the thread picks it up as part of its job loop.
From the JavaScript perspective, the timeout function is a new thread, it could become a multi-threaded application, if both threads ran longer. That it then becomes serialized in a single threaded engine is a different matter.
4

You missunderstand the usage of setTimeout.

The correct implementation of what you are asking for is:

function doHomeWork(subject, callback){
 setTimeout(callback,500);
 console.log("doing my homework:", subject)
}
doHomeWork("Maths", function(){console.log("finished my homework");});

When you invoke doHomeWork it you do two things (two lines of code): 1. Say the browser to add a the callback as a new task to be executed after 500ms. 2. Print console.log(...)

After 500ms, the browser will add a new task with the callback that will be invoked.

answered Mar 23, 2019 at 14:46

Comments

1

Easier for a Callback beginner without own function

setTimeout(() => {
console.log('finish homework')
}, 500);
console.log('start homework')

Output:

start hw
finish hw

The queue will go through the code including start hw , and then later execute the timeout-code inside setTimeout() with finish hw. The reason for this upside-down time behaviour is that inside function setTimeout(callback){ ... callback() ...} the callback() function is called which is later than the execution of the main thread which is written by you.

answered Mar 17, 2022 at 16:34

Comments

0

If you want to wait before that callback especially if callback is API call then create a separate function and return resolved promise from inside a setTimeout from that function, and use async await to await that wait function before doing API calls.

If you didn't get something then you can ask for further explanation.

Putzi San
6,4414 gold badges22 silver badges40 bronze badges
answered Jun 18, 2020 at 7:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.