为什么settimeout会阻塞eventloop [英] why settimeout blocks eventloop

查看:272
本文介绍了为什么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/1http://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.

这篇关于为什么settimeout会阻塞eventloop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆