Rus*_*lia 1 javascript asynchronous event-loop settimeout node.js
我编写了下面的程序,努力理解事件循环和setTimeout和setInterval等函数.
该计划的输出与我的预期不同:
输出是:
In F
In L
Padalia
outside all
callback1
callback2
From Interval:0
From Interval:1
From Interval:2
From Interval:3
Run Code Online (Sandbox Code Playgroud)
问题:
程序:
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();
Run Code Online (Sandbox Code Playgroud)
您在设置F和L超时的代码中有一个错误.您的代码等同于:
/* ... */
F(function(){
console.log("callback1");
});
setTimeout(undefined ,5000);
L(function(){
console.log("callback2");
});
setTimeout(undefined, 5000);
/* ... */
Run Code Online (Sandbox Code Playgroud)
现在应该清楚为什么你的程序没有像你期望的那样运行:
F和L之前.undefined回调设置的两个超时,程序等待5秒.如何修复代码的最简单方法是为setTimeout调用添加匿名回调函数:
setTimeout(function() { F(function(){
console.log("callback1");
})},5000);
setTimeout(function() { L(function(){
console.log("callback2");
})} , 5000);
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用bindfixate F和Lparameters(第一个参数bind是值this):
setTimeout(F.bind(null, (function(){
console.log("callback1");
})),5000);
setTimeout(L.bind(null, (function(){
console.log("callback2");
})) , 5000);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4622 次 |
| 最近记录: |