Callback not waiting for previous function to finish.
If callbacks are supposed to allow one function to wait for another function to finish before being called, why does the following not work?
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`)
, 1000)
callback()
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
This outputs the following:
Homework Finished!
Starting my chemistry homework.
But it should be the other way around. Why doesn't the callback wait for the setTimeout to finish before being called?
javascript
add a comment |
If callbacks are supposed to allow one function to wait for another function to finish before being called, why does the following not work?
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`)
, 1000)
callback()
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
This outputs the following:
Homework Finished!
Starting my chemistry homework.
But it should be the other way around. Why doesn't the callback wait for the setTimeout to finish before being called?
javascript
Try reading Up and Running with Asynchronous JavaScript
– Rafael
Nov 15 '18 at 1:13
1
That's because you are callingcallback
outside of thesetTimeout
callback. "Why doesn't the callback wait for the setTimeout to finish before being called?" Because that's not howsetTimeout
(or any async code) works. If you want A to happen after B is done, you have to execute A when B tells you that it is done. WhensetTimeout
is done, it calls the callback passed to it.
– Felix Kling
Nov 15 '18 at 1:14
Recommended watching: video
– jhpratt
Nov 15 '18 at 1:28
add a comment |
If callbacks are supposed to allow one function to wait for another function to finish before being called, why does the following not work?
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`)
, 1000)
callback()
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
This outputs the following:
Homework Finished!
Starting my chemistry homework.
But it should be the other way around. Why doesn't the callback wait for the setTimeout to finish before being called?
javascript
If callbacks are supposed to allow one function to wait for another function to finish before being called, why does the following not work?
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`)
, 1000)
callback()
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
This outputs the following:
Homework Finished!
Starting my chemistry homework.
But it should be the other way around. Why doesn't the callback wait for the setTimeout to finish before being called?
javascript
javascript
edited Nov 15 '18 at 1:24
gman
48.8k17114205
48.8k17114205
asked Nov 15 '18 at 1:08
CyberneticCybernetic
3,41394366
3,41394366
Try reading Up and Running with Asynchronous JavaScript
– Rafael
Nov 15 '18 at 1:13
1
That's because you are callingcallback
outside of thesetTimeout
callback. "Why doesn't the callback wait for the setTimeout to finish before being called?" Because that's not howsetTimeout
(or any async code) works. If you want A to happen after B is done, you have to execute A when B tells you that it is done. WhensetTimeout
is done, it calls the callback passed to it.
– Felix Kling
Nov 15 '18 at 1:14
Recommended watching: video
– jhpratt
Nov 15 '18 at 1:28
add a comment |
Try reading Up and Running with Asynchronous JavaScript
– Rafael
Nov 15 '18 at 1:13
1
That's because you are callingcallback
outside of thesetTimeout
callback. "Why doesn't the callback wait for the setTimeout to finish before being called?" Because that's not howsetTimeout
(or any async code) works. If you want A to happen after B is done, you have to execute A when B tells you that it is done. WhensetTimeout
is done, it calls the callback passed to it.
– Felix Kling
Nov 15 '18 at 1:14
Recommended watching: video
– jhpratt
Nov 15 '18 at 1:28
Try reading Up and Running with Asynchronous JavaScript
– Rafael
Nov 15 '18 at 1:13
Try reading Up and Running with Asynchronous JavaScript
– Rafael
Nov 15 '18 at 1:13
1
1
That's because you are calling
callback
outside of the setTimeout
callback. "Why doesn't the callback wait for the setTimeout to finish before being called?" Because that's not how setTimeout
(or any async code) works. If you want A to happen after B is done, you have to execute A when B tells you that it is done. When setTimeout
is done, it calls the callback passed to it.– Felix Kling
Nov 15 '18 at 1:14
That's because you are calling
callback
outside of the setTimeout
callback. "Why doesn't the callback wait for the setTimeout to finish before being called?" Because that's not how setTimeout
(or any async code) works. If you want A to happen after B is done, you have to execute A when B tells you that it is done. When setTimeout
is done, it calls the callback passed to it.– Felix Kling
Nov 15 '18 at 1:14
Recommended watching: video
– jhpratt
Nov 15 '18 at 1:28
Recommended watching: video
– jhpratt
Nov 15 '18 at 1:28
add a comment |
2 Answers
2
active
oldest
votes
You'll need to understand JS's execution model. Since JS was intended to run in a GUI, it is event driven thus runs in an event loop. This means that the main thread is executing your script, but other threads may work on ready-work enqueued by the main thread.
for (;;)
if event = dequeueWork()
handleEvent(event)
else
sleep(SOME_TIME)
When your script is interpreted, the JS engine knows that doHomework()
has a timeout event registration. Timeouts are like sleeps in other languages, but because this is an event-loop model, we cannot block the GUI. So this function actually is handled by a background thread. When the duration has elapsed, then the main thread is notified -- this is how all IO is handled in JS.
Understanding this, it's easy to see what's happening: the callback is being fired right after the timeout event was registered.
from c-sharpcorner.com
To fix this, as others have mentioned, you'll need to call the callback inside timeout's callback:
function doHomework(subject, callback)
console.log(`Starting my $subject homework.`)
setTimeout(function()
callback();
, 1000);
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
Of course we're all not lucky enough to finish our homework 1sec after starting ;)
Helpful resources:
- The Node.js Event Loop
- v8
- SpiderMonkey
But if I place the callback inside setTimeout, then there is no proof that callbacks wait for something to be finished. In this case, my callback is acting like any other function, getting called in the order it's written, but not waiting for anything to finish.
– Cybernetic
Nov 15 '18 at 1:23
Please reread my answer or the recommended article carefully. If you still have questions, I'll be happy to elaborate.
– Rafael
Nov 15 '18 at 1:26
1
If I understand you correctly, you are wondering why your function isn't asynchronous while setTimeout is. This is a great question. Callbacks are only used to handle async code, however, not define async code. setTimeout is async out-of-the-box (provided by the js std lib) just like XMLHttpRequest (as you noted). Please read the article I recommended carefully. As an aside, when you use an async function, directly or indirectly, the caller is also considered async.
– Rafael
Nov 15 '18 at 3:35
1
@Cybernetic: Technically a "callback" is just a function passed to another function and is called by that other function. A function you pass toArray#map
is a also a callback (i.e.[1,2,3].map(x => x + 1)
). There is no implication whatsoever when/how it is executed. That is at the discretion of the function that receives the callback.
– Felix Kling
Nov 15 '18 at 5:37
1
@Cybernetic Yes exactly :) One last thing (for clarification), you don't have to guess when a previous async function finishes since you can always perform side-effects in its callback (like callingcallback()
insetTimeout
's callback above). In this way, you can force an execution order without blocking the main thread. Unfortunately, calling callbacks within callbacks within callbacks, and so on, is known as callback hell and is ill-advised. Promises are the standard abstraction to mitigate this (by chainingthen
s).
– Rafael
Nov 15 '18 at 5:39
|
show 5 more comments
A callback
is the name of something which is executed in the future, your callback is not being executed in the future, is being executed right after calling the function setTimeout
.
What you actually want to do is call the function finishHomework
one second in the future, therefore, you have to put that callback
within the handler of the function setTimeout
as follow:
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`);
// Here depends of your needs, in this case the callback
// will be called after all the previous logic is executed.
callback()
, 1000)
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311034%2fcallback-not-waiting-for-previous-function-to-finish%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You'll need to understand JS's execution model. Since JS was intended to run in a GUI, it is event driven thus runs in an event loop. This means that the main thread is executing your script, but other threads may work on ready-work enqueued by the main thread.
for (;;)
if event = dequeueWork()
handleEvent(event)
else
sleep(SOME_TIME)
When your script is interpreted, the JS engine knows that doHomework()
has a timeout event registration. Timeouts are like sleeps in other languages, but because this is an event-loop model, we cannot block the GUI. So this function actually is handled by a background thread. When the duration has elapsed, then the main thread is notified -- this is how all IO is handled in JS.
Understanding this, it's easy to see what's happening: the callback is being fired right after the timeout event was registered.
from c-sharpcorner.com
To fix this, as others have mentioned, you'll need to call the callback inside timeout's callback:
function doHomework(subject, callback)
console.log(`Starting my $subject homework.`)
setTimeout(function()
callback();
, 1000);
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
Of course we're all not lucky enough to finish our homework 1sec after starting ;)
Helpful resources:
- The Node.js Event Loop
- v8
- SpiderMonkey
But if I place the callback inside setTimeout, then there is no proof that callbacks wait for something to be finished. In this case, my callback is acting like any other function, getting called in the order it's written, but not waiting for anything to finish.
– Cybernetic
Nov 15 '18 at 1:23
Please reread my answer or the recommended article carefully. If you still have questions, I'll be happy to elaborate.
– Rafael
Nov 15 '18 at 1:26
1
If I understand you correctly, you are wondering why your function isn't asynchronous while setTimeout is. This is a great question. Callbacks are only used to handle async code, however, not define async code. setTimeout is async out-of-the-box (provided by the js std lib) just like XMLHttpRequest (as you noted). Please read the article I recommended carefully. As an aside, when you use an async function, directly or indirectly, the caller is also considered async.
– Rafael
Nov 15 '18 at 3:35
1
@Cybernetic: Technically a "callback" is just a function passed to another function and is called by that other function. A function you pass toArray#map
is a also a callback (i.e.[1,2,3].map(x => x + 1)
). There is no implication whatsoever when/how it is executed. That is at the discretion of the function that receives the callback.
– Felix Kling
Nov 15 '18 at 5:37
1
@Cybernetic Yes exactly :) One last thing (for clarification), you don't have to guess when a previous async function finishes since you can always perform side-effects in its callback (like callingcallback()
insetTimeout
's callback above). In this way, you can force an execution order without blocking the main thread. Unfortunately, calling callbacks within callbacks within callbacks, and so on, is known as callback hell and is ill-advised. Promises are the standard abstraction to mitigate this (by chainingthen
s).
– Rafael
Nov 15 '18 at 5:39
|
show 5 more comments
You'll need to understand JS's execution model. Since JS was intended to run in a GUI, it is event driven thus runs in an event loop. This means that the main thread is executing your script, but other threads may work on ready-work enqueued by the main thread.
for (;;)
if event = dequeueWork()
handleEvent(event)
else
sleep(SOME_TIME)
When your script is interpreted, the JS engine knows that doHomework()
has a timeout event registration. Timeouts are like sleeps in other languages, but because this is an event-loop model, we cannot block the GUI. So this function actually is handled by a background thread. When the duration has elapsed, then the main thread is notified -- this is how all IO is handled in JS.
Understanding this, it's easy to see what's happening: the callback is being fired right after the timeout event was registered.
from c-sharpcorner.com
To fix this, as others have mentioned, you'll need to call the callback inside timeout's callback:
function doHomework(subject, callback)
console.log(`Starting my $subject homework.`)
setTimeout(function()
callback();
, 1000);
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
Of course we're all not lucky enough to finish our homework 1sec after starting ;)
Helpful resources:
- The Node.js Event Loop
- v8
- SpiderMonkey
But if I place the callback inside setTimeout, then there is no proof that callbacks wait for something to be finished. In this case, my callback is acting like any other function, getting called in the order it's written, but not waiting for anything to finish.
– Cybernetic
Nov 15 '18 at 1:23
Please reread my answer or the recommended article carefully. If you still have questions, I'll be happy to elaborate.
– Rafael
Nov 15 '18 at 1:26
1
If I understand you correctly, you are wondering why your function isn't asynchronous while setTimeout is. This is a great question. Callbacks are only used to handle async code, however, not define async code. setTimeout is async out-of-the-box (provided by the js std lib) just like XMLHttpRequest (as you noted). Please read the article I recommended carefully. As an aside, when you use an async function, directly or indirectly, the caller is also considered async.
– Rafael
Nov 15 '18 at 3:35
1
@Cybernetic: Technically a "callback" is just a function passed to another function and is called by that other function. A function you pass toArray#map
is a also a callback (i.e.[1,2,3].map(x => x + 1)
). There is no implication whatsoever when/how it is executed. That is at the discretion of the function that receives the callback.
– Felix Kling
Nov 15 '18 at 5:37
1
@Cybernetic Yes exactly :) One last thing (for clarification), you don't have to guess when a previous async function finishes since you can always perform side-effects in its callback (like callingcallback()
insetTimeout
's callback above). In this way, you can force an execution order without blocking the main thread. Unfortunately, calling callbacks within callbacks within callbacks, and so on, is known as callback hell and is ill-advised. Promises are the standard abstraction to mitigate this (by chainingthen
s).
– Rafael
Nov 15 '18 at 5:39
|
show 5 more comments
You'll need to understand JS's execution model. Since JS was intended to run in a GUI, it is event driven thus runs in an event loop. This means that the main thread is executing your script, but other threads may work on ready-work enqueued by the main thread.
for (;;)
if event = dequeueWork()
handleEvent(event)
else
sleep(SOME_TIME)
When your script is interpreted, the JS engine knows that doHomework()
has a timeout event registration. Timeouts are like sleeps in other languages, but because this is an event-loop model, we cannot block the GUI. So this function actually is handled by a background thread. When the duration has elapsed, then the main thread is notified -- this is how all IO is handled in JS.
Understanding this, it's easy to see what's happening: the callback is being fired right after the timeout event was registered.
from c-sharpcorner.com
To fix this, as others have mentioned, you'll need to call the callback inside timeout's callback:
function doHomework(subject, callback)
console.log(`Starting my $subject homework.`)
setTimeout(function()
callback();
, 1000);
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
Of course we're all not lucky enough to finish our homework 1sec after starting ;)
Helpful resources:
- The Node.js Event Loop
- v8
- SpiderMonkey
You'll need to understand JS's execution model. Since JS was intended to run in a GUI, it is event driven thus runs in an event loop. This means that the main thread is executing your script, but other threads may work on ready-work enqueued by the main thread.
for (;;)
if event = dequeueWork()
handleEvent(event)
else
sleep(SOME_TIME)
When your script is interpreted, the JS engine knows that doHomework()
has a timeout event registration. Timeouts are like sleeps in other languages, but because this is an event-loop model, we cannot block the GUI. So this function actually is handled by a background thread. When the duration has elapsed, then the main thread is notified -- this is how all IO is handled in JS.
Understanding this, it's easy to see what's happening: the callback is being fired right after the timeout event was registered.
from c-sharpcorner.com
To fix this, as others have mentioned, you'll need to call the callback inside timeout's callback:
function doHomework(subject, callback)
console.log(`Starting my $subject homework.`)
setTimeout(function()
callback();
, 1000);
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
Of course we're all not lucky enough to finish our homework 1sec after starting ;)
Helpful resources:
- The Node.js Event Loop
- v8
- SpiderMonkey
function doHomework(subject, callback)
console.log(`Starting my $subject homework.`)
setTimeout(function()
callback();
, 1000);
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
function doHomework(subject, callback)
console.log(`Starting my $subject homework.`)
setTimeout(function()
callback();
, 1000);
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
edited Nov 15 '18 at 1:51
answered Nov 15 '18 at 1:20
RafaelRafael
4,786102339
4,786102339
But if I place the callback inside setTimeout, then there is no proof that callbacks wait for something to be finished. In this case, my callback is acting like any other function, getting called in the order it's written, but not waiting for anything to finish.
– Cybernetic
Nov 15 '18 at 1:23
Please reread my answer or the recommended article carefully. If you still have questions, I'll be happy to elaborate.
– Rafael
Nov 15 '18 at 1:26
1
If I understand you correctly, you are wondering why your function isn't asynchronous while setTimeout is. This is a great question. Callbacks are only used to handle async code, however, not define async code. setTimeout is async out-of-the-box (provided by the js std lib) just like XMLHttpRequest (as you noted). Please read the article I recommended carefully. As an aside, when you use an async function, directly or indirectly, the caller is also considered async.
– Rafael
Nov 15 '18 at 3:35
1
@Cybernetic: Technically a "callback" is just a function passed to another function and is called by that other function. A function you pass toArray#map
is a also a callback (i.e.[1,2,3].map(x => x + 1)
). There is no implication whatsoever when/how it is executed. That is at the discretion of the function that receives the callback.
– Felix Kling
Nov 15 '18 at 5:37
1
@Cybernetic Yes exactly :) One last thing (for clarification), you don't have to guess when a previous async function finishes since you can always perform side-effects in its callback (like callingcallback()
insetTimeout
's callback above). In this way, you can force an execution order without blocking the main thread. Unfortunately, calling callbacks within callbacks within callbacks, and so on, is known as callback hell and is ill-advised. Promises are the standard abstraction to mitigate this (by chainingthen
s).
– Rafael
Nov 15 '18 at 5:39
|
show 5 more comments
But if I place the callback inside setTimeout, then there is no proof that callbacks wait for something to be finished. In this case, my callback is acting like any other function, getting called in the order it's written, but not waiting for anything to finish.
– Cybernetic
Nov 15 '18 at 1:23
Please reread my answer or the recommended article carefully. If you still have questions, I'll be happy to elaborate.
– Rafael
Nov 15 '18 at 1:26
1
If I understand you correctly, you are wondering why your function isn't asynchronous while setTimeout is. This is a great question. Callbacks are only used to handle async code, however, not define async code. setTimeout is async out-of-the-box (provided by the js std lib) just like XMLHttpRequest (as you noted). Please read the article I recommended carefully. As an aside, when you use an async function, directly or indirectly, the caller is also considered async.
– Rafael
Nov 15 '18 at 3:35
1
@Cybernetic: Technically a "callback" is just a function passed to another function and is called by that other function. A function you pass toArray#map
is a also a callback (i.e.[1,2,3].map(x => x + 1)
). There is no implication whatsoever when/how it is executed. That is at the discretion of the function that receives the callback.
– Felix Kling
Nov 15 '18 at 5:37
1
@Cybernetic Yes exactly :) One last thing (for clarification), you don't have to guess when a previous async function finishes since you can always perform side-effects in its callback (like callingcallback()
insetTimeout
's callback above). In this way, you can force an execution order without blocking the main thread. Unfortunately, calling callbacks within callbacks within callbacks, and so on, is known as callback hell and is ill-advised. Promises are the standard abstraction to mitigate this (by chainingthen
s).
– Rafael
Nov 15 '18 at 5:39
But if I place the callback inside setTimeout, then there is no proof that callbacks wait for something to be finished. In this case, my callback is acting like any other function, getting called in the order it's written, but not waiting for anything to finish.
– Cybernetic
Nov 15 '18 at 1:23
But if I place the callback inside setTimeout, then there is no proof that callbacks wait for something to be finished. In this case, my callback is acting like any other function, getting called in the order it's written, but not waiting for anything to finish.
– Cybernetic
Nov 15 '18 at 1:23
Please reread my answer or the recommended article carefully. If you still have questions, I'll be happy to elaborate.
– Rafael
Nov 15 '18 at 1:26
Please reread my answer or the recommended article carefully. If you still have questions, I'll be happy to elaborate.
– Rafael
Nov 15 '18 at 1:26
1
1
If I understand you correctly, you are wondering why your function isn't asynchronous while setTimeout is. This is a great question. Callbacks are only used to handle async code, however, not define async code. setTimeout is async out-of-the-box (provided by the js std lib) just like XMLHttpRequest (as you noted). Please read the article I recommended carefully. As an aside, when you use an async function, directly or indirectly, the caller is also considered async.
– Rafael
Nov 15 '18 at 3:35
If I understand you correctly, you are wondering why your function isn't asynchronous while setTimeout is. This is a great question. Callbacks are only used to handle async code, however, not define async code. setTimeout is async out-of-the-box (provided by the js std lib) just like XMLHttpRequest (as you noted). Please read the article I recommended carefully. As an aside, when you use an async function, directly or indirectly, the caller is also considered async.
– Rafael
Nov 15 '18 at 3:35
1
1
@Cybernetic: Technically a "callback" is just a function passed to another function and is called by that other function. A function you pass to
Array#map
is a also a callback (i.e. [1,2,3].map(x => x + 1)
). There is no implication whatsoever when/how it is executed. That is at the discretion of the function that receives the callback.– Felix Kling
Nov 15 '18 at 5:37
@Cybernetic: Technically a "callback" is just a function passed to another function and is called by that other function. A function you pass to
Array#map
is a also a callback (i.e. [1,2,3].map(x => x + 1)
). There is no implication whatsoever when/how it is executed. That is at the discretion of the function that receives the callback.– Felix Kling
Nov 15 '18 at 5:37
1
1
@Cybernetic Yes exactly :) One last thing (for clarification), you don't have to guess when a previous async function finishes since you can always perform side-effects in its callback (like calling
callback()
in setTimeout
's callback above). In this way, you can force an execution order without blocking the main thread. Unfortunately, calling callbacks within callbacks within callbacks, and so on, is known as callback hell and is ill-advised. Promises are the standard abstraction to mitigate this (by chaining then
s).– Rafael
Nov 15 '18 at 5:39
@Cybernetic Yes exactly :) One last thing (for clarification), you don't have to guess when a previous async function finishes since you can always perform side-effects in its callback (like calling
callback()
in setTimeout
's callback above). In this way, you can force an execution order without blocking the main thread. Unfortunately, calling callbacks within callbacks within callbacks, and so on, is known as callback hell and is ill-advised. Promises are the standard abstraction to mitigate this (by chaining then
s).– Rafael
Nov 15 '18 at 5:39
|
show 5 more comments
A callback
is the name of something which is executed in the future, your callback is not being executed in the future, is being executed right after calling the function setTimeout
.
What you actually want to do is call the function finishHomework
one second in the future, therefore, you have to put that callback
within the handler of the function setTimeout
as follow:
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`);
// Here depends of your needs, in this case the callback
// will be called after all the previous logic is executed.
callback()
, 1000)
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
add a comment |
A callback
is the name of something which is executed in the future, your callback is not being executed in the future, is being executed right after calling the function setTimeout
.
What you actually want to do is call the function finishHomework
one second in the future, therefore, you have to put that callback
within the handler of the function setTimeout
as follow:
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`);
// Here depends of your needs, in this case the callback
// will be called after all the previous logic is executed.
callback()
, 1000)
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
add a comment |
A callback
is the name of something which is executed in the future, your callback is not being executed in the future, is being executed right after calling the function setTimeout
.
What you actually want to do is call the function finishHomework
one second in the future, therefore, you have to put that callback
within the handler of the function setTimeout
as follow:
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`);
// Here depends of your needs, in this case the callback
// will be called after all the previous logic is executed.
callback()
, 1000)
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
A callback
is the name of something which is executed in the future, your callback is not being executed in the future, is being executed right after calling the function setTimeout
.
What you actually want to do is call the function finishHomework
one second in the future, therefore, you have to put that callback
within the handler of the function setTimeout
as follow:
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`);
// Here depends of your needs, in this case the callback
// will be called after all the previous logic is executed.
callback()
, 1000)
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`);
// Here depends of your needs, in this case the callback
// will be called after all the previous logic is executed.
callback()
, 1000)
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
function doHomework(subject, callback)
setTimeout(function()
console.log(`Starting my $subject homework.`);
// Here depends of your needs, in this case the callback
// will be called after all the previous logic is executed.
callback()
, 1000)
function finishHomework()
console.log('Homework Finished!')
doHomework('chemistry', finishHomework)
edited Nov 15 '18 at 1:24
answered Nov 15 '18 at 1:17
EleEle
24.8k52251
24.8k52251
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311034%2fcallback-not-waiting-for-previous-function-to-finish%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Try reading Up and Running with Asynchronous JavaScript
– Rafael
Nov 15 '18 at 1:13
1
That's because you are calling
callback
outside of thesetTimeout
callback. "Why doesn't the callback wait for the setTimeout to finish before being called?" Because that's not howsetTimeout
(or any async code) works. If you want A to happen after B is done, you have to execute A when B tells you that it is done. WhensetTimeout
is done, it calls the callback passed to it.– Felix Kling
Nov 15 '18 at 1:14
Recommended watching: video
– jhpratt
Nov 15 '18 at 1:28