为什么settimeout会阻塞eventloop
注意:这不是有关settimeout的重复帖子,此处的关键答案是浏览器设计选项.
Note: this is not a replicated post for those about settimeout, the key answer here is browser design options.
我正在研究node.js: 一个简单的异步测试示例:
I am starting study node.js: A simple example to test async:
var http=require('http');
http.createServer(
function(request, response){
response.writeHead(200);
response.write("Hello, dog is running");
setTimeout(
function(){
response.write("Dog is done");
response.end();
},
10000
);
}
).listen(8080);
console.log("Listen on port 8080")
一个有趣的事情是,在带有curl的命令lind和浏览器中,其行为是不同的: 在Ubuntu 12.10中,我在两个控制台中使用curl localhost:8080,它们在几乎相同的10个发送中进行响应.
One interesting thing is its behavior is differernt when in command lind with curl and in browser: In Ubuntu 12.10, I use curl localhost:8080 in two consoles, they response in almost same 10 sends.
但是,我打开了两个浏览器,几乎同时发出了请求,但是整个过程花了我20秒钟?
However, I open two browsers, make the request at almost same time, but the whole procedure took me 20 seconds?
谢谢.
正在等待浏览器,而不是node.js
It's the browser waiting, not node.js
如果您运行服务器并在两个选项卡中请求http://localhost:8080/
,则将花费20秒的时间,因为浏览器在启动第二个选项之前先等待对相同网址的第一个请求.
If you run the server and request http://localhost:8080/
in two tabs it takes 20 seconds because the browser waits for the first request to the same url before starting the second.
如果运行服务器并在两个选项卡中请求http://localhost:8080/1
和http://localhost:8080/2
,则将再次花费10秒钟.
If you run the server and request http://localhost:8080/1
and http://localhost:8080/2
in two tabs it takes 10 seconds again.