我有这个简单的节点服务器:
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 “fun” 每 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);
}
现在“乐趣”每三秒出现一次。