node.js和setTimeout和setInterval – 了解事件循环

为了理解事件循环和函数setTimeout和setInterval,我编写了下面的程序。

该程序的输出是不同于我的预期:

输出是:

In F In L Padalia outside all callback1 callback2 From Interval:0 From Interval:1 From Interval:2 From Interval:3 

问题:

  1. 为什么“全部”不是先执行?
  2. 为什么间隔总是最后执行?
  3. 有人可以向我解释整个程序的执行吗?
  4. 在退出程序之前等待一段时间,为什么?

程序:

 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(); 

您在代码中设置了FL超时的错误。 你的代码相当于这个:

 /* ... */ F(function(){ console.log("callback1"); }); setTimeout(undefined ,5000); L(function(){ console.log("callback2"); }); setTimeout(undefined, 5000); /* ... */ 

现在应该清楚为什么你的程序不像你所期望的那样:

  1. “外部全部”不是首先执行,因为您之前调用FL
  2. 间隔最后从相同的原因执行。
  3. 程序等待5秒钟,您设置了两个超时,并使用undefinedcallback。

如何解决你的代码最简单的方法是为setTimeout调用添加匿名callback函数:

  setTimeout(function() { F(function(){ console.log("callback1"); })},5000); setTimeout(function() { L(function(){ console.log("callback2"); })} , 5000); 

或者,你可以使用bind来固定FL参数( 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函数不会直接将parameter passing给你的函数,所以你需要在随后的参数中发送它们。

 setTimeout(function,milliseconds,param1,param2,...)