我有这个简单的节点服务器:
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);
}
现在“有趣”每三秒出现一次。
答案 0 :(得分:3)
因为你每3秒调用一次“有趣”的函数,所以它会在setTimeout回调中调用它自己。
答案 1 :(得分:3)
您最初是从http服务器的回调中调用fun()
。也就是说,每次http服务器处理http请求时,它都会再次调用fun()
。因此,在处理了两个http请求之后,将会有两个独立的有趣序列,你应该每三秒在控制台中看到两次“有趣”。在三个请求之后,您应该每三秒钟在控制台中看到“有趣”三次。在 x 请求之后,您应该每隔三秒在控制台中看到“有趣的” x 次。
答案 2 :(得分:2)
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请求。这些是请求的URL。
/
/favicon.ico
您可以阅读favicon
here。因此,两个请求都将计时器设置为3秒。这就是为什么你看到fun
被打印两次。