node.js和setTimeout以及setInterval - 理解事件循环

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)

问题:

  1. 为什么"oustside all"不是先执行?
  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();
Run Code Online (Sandbox Code Playgroud)

Mir*_*toš 5

您在设置FL超时的代码中有一个错误.您的代码等同于:

/* ... */

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

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

/* ... */
Run Code Online (Sandbox Code Playgroud)

现在应该清楚为什么你的程序没有像你期望的那样运行:

  1. "以外的所有"是不是第一,因为你是在调用执行FL之前.
  2. 由于同样的原因,最后执行间隔.
  3. 对于您使用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 FLparameters(第一个参数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)