【发布时间】:2013-06-14 06:20:35
【问题描述】:
我编写了下面的程序,以努力理解事件循环和 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();
【问题讨论】:
标签: javascript node.js asynchronous settimeout event-loop