Reputation: 3103
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");});
Upvotes: 5
Views: 20821
Reputation: 3217
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.
Upvotes: 1
Reputation: 1
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.
Upvotes: 0
Reputation: 101
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);
Upvotes: 5
Reputation: 343
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.
Upvotes: 4