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:
- Why is "oustside all" not execution first?
- Why is the interval always executing last?
- Can someone explain me the execution of the entire program.
- 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();