Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have written the program below in efforts to understand the event-loop and functions like setTimeout and setInterval.

The output of the program is different from What I expected:

The output is:

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

QUESTIONS:

  1. Why is "oustside all" not execution first?
  2. Why is the interval always executing last?
  3. Can someone explain me the execution of the entire program.
  4. Before exiting the program waits for sometime, why?

PROGRAM:

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();
share|improve this question

1 Answer

up vote 4 down vote accepted

You have a bug in the code where you set F and L timeouts. Your code is equivalent to this:

/* ... */

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

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

/* ... */

Now it should be clear why your program does not behave as you were expecting:

  1. "Outside all" is not executed first because you are calling F and L before.
  2. The interval is executed last from the same reason.
  3. The program waits 5 seconds for the two timeouts you set with undefined callback.

The easiest way how to fix your code is to add anonymous callback function for setTimeout calls:

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

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

Alternatively, you can use bind to fixate F and L parameters (the first parameter of bind is value for this):

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

setTimeout(L.bind(null, (function(){
 console.log("callback2");
})) , 5000);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.