[英]What's the purpose of callback function if code skips macrotasks?
Recently, I've tried to understand callback functions in JavaScript, however, this concept is still far away from my understanding.最近尝试理解JavaScript中的回调函数,但是这个概念离我的理解还很远。 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.我预计在调用
exampleFunc()
后,程序将等待 3 秒,然后调用回调和代码 rest。 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."
我预计该程序将 output
"Starting"
,然后等待并记录"Logged after 3 secs."
, then go to callback and output "Further code"
, and in the end, "Log it!"
, 然后 go 回调和 output
"Further code"
, 最后, "Log it!"
. .
Calling a setTimeout
does not cause further execution of the code in that function to delay.调用
setTimeout
不会导致 function 中的代码进一步执行延迟。 setTimeout
schedules a timeout, then continues executing the rest of the code in the function immediately . setTimeout
安排一个超时时间,然后立即继续执行 function 中代码的rest 。
You need to call callback
inside the setTimeout
callback, so that it runs only after the 3 seconds are up.您需要在
setTimeout
回调中调用callback
,以便它仅在 3 秒后运行。
You also need to put the call of displayMessage
inside the callback passed to exampleFunc
.您还需要将
displayMessage
的调用放在传递给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(); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.