![](/img/trans.png)
[英]What will be executed first in Node.js/Javascript Event Loop among setInterval(()=>{}, 5000) and setTimeout(()=>{}, 5000)?
[英]node.js and setTimeout and setInterval - understanding event loop
我在下面编写了程序,以了解事件循环和setTimeout和setInterval之类的功能。
该程序的输出与我预期的不同:
输出为:
In F
In L
Padalia
outside all
callback1
callback2
From Interval:0
From Interval:1
From Interval:2
From Interval:3
问题:
程序:
var Fname = undefined;
var Lname = undefined;
var count = 0;
function F(callback){
console.log("In F");
Fname = "Rushabh";
if(Fname != undefined && Lname != undefined) {
console.log(Fname);
}
process.nextTick(function() {
callback();
});
//callback();
}
function L(callback){
console.log("In L");
Lname = "Padalia";
if(Fname != undefined && Lname != undefined) {
console.log(Lname);
}
process.nextTick(function() {callback();});
//callback();
}
function compute(){
Id = setInterval(function() {
console.log("From Interval:" + count); count++;
if(count > 3){
clearInterval(Id);
}
}, 100)
setTimeout(F(function(){
console.log("callback1");
}),5000);
setTimeout(L(function(){
console.log("callback2");
}) , 5000);
console.log("Outside all");
}
compute();
您在设置F
和L
超时的代码中有一个错误。 您的代码与此等效:
/* ... */
F(function(){
console.log("callback1");
});
setTimeout(undefined ,5000);
L(function(){
console.log("callback2");
});
setTimeout(undefined, 5000);
/* ... */
现在应该很清楚为什么您的程序不按预期运行:
F
和L
,所以不会首先执行“全部”。 undefined
回调设置的两个超时等待5秒。 修复代码的最简单方法是为setTimeout
调用添加匿名回调函数:
setTimeout(function() { F(function(){
console.log("callback1");
})},5000);
setTimeout(function() { L(function(){
console.log("callback2");
})} , 5000);
另外,您可以使用bind
固定F
和L
参数( bind
的第一个参数是this
值):
setTimeout(F.bind(null, (function(){
console.log("callback1");
})),5000);
setTimeout(L.bind(null, (function(){
console.log("callback2");
})) , 5000);
您还可以如下更改setTimeout,
...
setTimeout(F,5000,function(){
console.log("callback1");
});
setTimeout(L,5000,function(){
console.log("callback2");
});
...
由于setTimeout函数不会将参数直接带到函数中,因此需要在后续参数中发送它们。
setTimeout(function,milliseconds,param1,param2,...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.