Why console.log() is called two times instead of one?

Problem

I've this simple node server:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
  fun();
}).listen(9999, '127.0.0.1');

function fun () {
  setTimeout(function(){
    fun();
    console.log('fun');
  }, 3000);
}

console.log('Server running at 127.0.0.1:9999');

But opening 127.0.0.1:9999 "fun" appears two times each 3 second, instead of just one time. Why?


Solved:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(9998, '127.0.0.1');

fun();

function fun() {
        setTimeout(function(){
                fun();
                console.log('fun');
        }, 3000);
}

Now "fun" appears one time each three seconds.

Problem courtesy of: sensorario

Solution

You initially call fun() from within your http server's callback. That is, each time the http server handles an http request it will call fun() again. So after two http requests have been processed there will be two separate fun sequences going and you should see "fun" in the console twice every three seconds. After three requests you should see "fun" in the console three times every three seconds. After x requests you should see "fun" x times in the console every three seconds.

Solution courtesy of: nnnnnn

Discussion

Mystery Resolved.

http.createServer(function (req, res) {
  console.log(req.url);                              //Printing the requested URL
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('ello World\n');
  fun();
}).listen(9999, '127.0.0.1');

I printed the URL when a request comes in and it turns out that there are two HTTP requests coming in for every human request. These are the URLs requested.

/
/favicon.ico

You can read about favicon here. So, both the requests set the timers to 3 seconds. Thats why you see that fun getting printed twice.

Discussion courtesy of: thefourtheye

Because you're calling the function "fun" every 3 second, it's calling itself inside the setTimeout callback.

Discussion courtesy of: OneOfOne

This recipe can be found in it's original form on Stack Over Flow.