why settimeout blocks eventloop

why settimeout blocks eventloop

Problem

Note: this is not a replicated post for those about settimeout, the key answer here is browser design options.

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") 

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.

However, I open two browsers, make the request at almost same time, but the whole procedure took me 20 seconds?

thanks.

Problem courtesy of: Kuan

Solution

It’s the browser waiting, not node.js

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.

If you run the server and request http://localhost:8080/1 and http://localhost:8080/2 in two tabs it takes 10 seconds again.

Solution courtesy of: generalhenry

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *