为什么 console.log() 被调用两次而不是一次

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

本文关键字:一次 两次 console log 调用 为什么      更新时间:2023-09-26

我有这个简单的节点服务器:

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

但是打开 127.0.0.1:9999 "乐趣"每 3 秒出现两次,而不仅仅是一次。为什么?


解决:

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

现在,"有趣"每三秒出现一次。

您最初从 http 服务器的回调中调用fun()。也就是说,每次 http 服务器处理 http 请求时,它都会再次调用fun()。因此,在处理了两个http请求后,将有两个单独的有趣序列,您应该每三秒在控制台中看到两次"fun"。在三次请求后,您应该每三秒在控制台中看到三次"有趣"。 x 请求后,您应该每三秒在控制台中看到 x 次"有趣"。

因为你每 3 秒调用一次函数"fun",所以它在 setTimeout 回调中调用自身。

谜团已解开。

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

当请求进来时,我打印了URL,结果发现每个人工请求都有两个HTTP请求。这些是请求的网址。

/
/favicon.ico

您可以在此处阅读有关favicon的信息。 因此,两个请求都将计时器设置为 3 秒。这就是为什么你看到fun被打印两次。