[英]JavaScript CallBack Function ..ish issue
So I was doing some practice about callback function and I wanted to try it out in my own was and use it with a setTimeout Method and to my surprise, it didn't work as expected.. Pls what am i doing wrong here. 因此,我正在做一些有关回调函数的练习,我想自己尝试一下并将其与setTimeout方法一起使用,但令我惊讶的是,它没有按预期工作。.请问我在这里做错了什么。
function first(number, callback) { setTimeout(function() { console.log(number); }, 5); callback(); } function second() { console.log(2); } first(1, second);
You're executing setTimeout
and callback
at the same time. 您正在同时执行setTimeout
和callback
。 Because JavaScript is single-threaded, it doesn't wait for setTimeout
to complete before executing the next statement. 因为JavaScript是单线程的,所以它不等待setTimeout
完成才执行下setTimeout
语句。
That's why, 2
prints immediately, and then 1
prints after a delay of 5 milliseconds. 因此,立即打印2
张,然后在5毫秒的延迟后打印1
张。
If you want to print 1
first, then you need to call the callback
function in the callback of setTimeout
. 如果要先打印1
,则需要在setTimeout
的回调中调用callback
函数。 This ensures that the console.log(number)
executes prior to calling the callback
(which prints 2
). 这样可以确保console.log(number)
在调用callback
之前执行(打印2
)。
function first(number, callback) { setTimeout(function() { console.log(number); callback(); }, 5); } function second() { console.log(2); } first(1, second);
As 31piy already said, setTimeout()
and callback()
are being executed at the same time. 正如31piy已经说过的那样, setTimeout()
和callback()
正在同时执行。 Your code first schedules a function execution at 5ms from now, and then immediately runs another function that logs 2
to the console. 您的代码首先计划从现在起5毫秒执行一次函数执行,然后立即运行另一个将2
记录到控制台的函数。
You can achieve the expected result in a couple of similar ways, I'll show one: 您可以通过两种类似的方法来达到预期的效果,我将展示一种:
function first(number,callback) { setTimeout(function() { callback(); }, 5); console.log(number); } function second() { console.log(2); } first(1, second); //Here, you immediately print the number 1 and schedule the number 2.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.