Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

node.js and setTimeout and google chrome

node.js and setTimeout and google chrome

Problem

I am a beginner in node.js I have some problems with setTimeout(function(){.....},time); thingo. This works fine when i curl the local server but not as expected in google chrome (i haven't tested other browsers)

My Code is:

/* simple node.js createserver */

var http = require('http');

http.createServer(function (request, response) {
     response.writeHead(200);
  response.write('Somthing\r\n');

  setTimeout(function(){
        response.end('\n This came out after 5 seconds :) ');
  }, 5000);
   response.write('Hello World\n');
}).listen(8124);



console.log('Server running at http://127.0.0.1:8124/');

When i curl 127.0.0.1:8124 everything works as expected. But when i point that in browser, it remains idle for some time (which i guess is that 5 seconds) and shows all the contents at once? Is this the expected behavior of node.js or i am missing something? Can the browser do thing like the curl does (i.e, printing two lines first, and waiting for 5 seconds and printing another line)?

Problem courtesy of: cipher

Solution

Try this

http.createServer(function (request, response)

  response.setHeader('Content-Type', 'text/html; charset=UTF-8');
  response.writeHead(200);
  response.write('Somthing\r\n');

  setTimeout(function(){
    response.end('\n This came out after 5 seconds :) ');
  }, 5000);

  response.write('Hello World\n');
  //No point writing Hello World here as it is written immediately

}).listen(8124);
Solution courtesy of: user568109

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

node.js and setTimeout and google chrome

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×