Recently, I've tried to understand callback functions in JavaScript, however, this concept is still far away from my understanding. I have code like this:
function exampleFunc(callback) {
console.log("Starting...");
setTimeout(() => {
console.log("Logged after 3 secs.");
}, 3000);
callback();
}
function displayMessage() {
console.log("Log it!");
}
exampleFunc(() =>
{
console.log("Further code.");
});
displayMessage();
I've expected that after calling exampleFunc()
, program will wait 3 seconds, and then call the callback and rest of code. But instead, the sequence of code is:
Starting...
Further code.
Log it!
Logged after 3 secs.
Why does it happen? I've expected that program will output "Starting"
, then wait and log "Logged after 3 secs."
, then go to callback and output "Further code"
, and in the end, "Log it!"
.
Calling a setTimeout
does not cause further execution of the code in that function to delay. setTimeout
schedules a timeout, then continues executing the rest of the code in the function immediately .
You need to call callback
inside the setTimeout
callback, so that it runs only after the 3 seconds are up.
You also need to put the call of displayMessage
inside the callback passed to exampleFunc
.
function exampleFunc(callback) { console.log("Starting..."); setTimeout(() => { console.log("Logged after 3 secs."); callback(); }, 3000); } function displayMessage() { console.log("Log it;"). } exampleFunc(() => { console.log("Further code;"); displayMessage(); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.