0

I am learning Node.js and was trying a simple example of setTimeout(). What is supposed to happen is:

"Dog is running." (5 seconds later) "Dog is done."

But when i run the code, the program runs for 5 seconds and prints both statements. I am not sure why this is happening. My code is below:

var http = require('http');

http.createServer(function(request, response) {
  response.writeHead(200);
  response.write("Dog is running.\n");
  setTimeout(function(){
  response.write("Dog is done.");
  response.end();
  }, 5000);
}).listen(8080);

console.log("Server started!!!")
2
  • The response is sent when response.end() is executed.That's why both statements are printed at the same time. Commented Feb 14, 2014 at 20:45
  • so what can i change so that 'Dog is running' is printed, server waits 5 seconds and then prints 'Dog is done' Commented Feb 14, 2014 at 20:55

2 Answers 2

3

You can fix it adding these 3 headers to the response:

response.setHeader('Connection', 'Transfer-Encoding');
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.setHeader('Transfer-Encoding', 'chunked');

It would be like this:

var http = require('http');

http.createServer(function(request, response) {
  response.setHeader('Connection', 'Transfer-Encoding');
    response.setHeader('Content-Type', 'text/html; charset=utf-8');
    response.setHeader('Transfer-Encoding', 'chunked');
  setTimeout(function(){
    response.write("Dog is done.");
    response.end();
  }, 5000);
  response.write("Dog is running.\n");
}).listen(8080);

console.log("Server started!!!")
Sign up to request clarification or add additional context in comments.

Comments

1

Your code is perfectly fine, and there is nothing wrong with it. Node.js adds chunked headers by default so previous answers are all wrong.

You can try it for yourself using telnet:

$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.1

HTTP/1.1 200 OK
Date: Sat, 15 Feb 2014 00:02:02 GMT
Connection: keep-alive
Transfer-Encoding: chunked

10
Dog is running.

c
Dog is done.
0

The issue here is that most browsers buffer incoming data, so it won't be displayed until the page is fully loaded.

You can try to combat this by increasing a message (adding kilobytes of whitespace or something like that).

But if you're just testing setTimeout, don't worry about that. Just test it using telnet, not regular browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.