[英]Why console.log() is called two times instead of one?
我有這個簡單的節點服務器:
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);
}
現在,“樂趣”每三秒鍾出現一次。
因為您每3秒調用一次函數“ fun”,所以它會在setTimeout回調內部進行自身調用。
您最初是從HTTP服務器的回調中調用fun()
的。 也就是說,每次http服務器處理http請求時,它將再次調用fun()
。 因此,在處理了兩個http請求之后,將會有兩個單獨的有趣序列,您應該每三秒鍾在控制台中看到兩次“ fun”。 在三個請求之后,您應該每三秒鍾在控制台中看到三遍“ fun”。 x請求之后,您應該每三秒鍾在控制台中看到x次“ fun”。
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
信息 。 因此,兩個請求都將計時器設置為3秒。 這就是為什么您會看到兩次打印fun
原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.