Jack
Jack

Reputation: 629

how to use setTimeout asynchronously in node.js

I'm new to node.js, I tried to use setTimeout to simulate long connections and hope it act asynchronously.

var http = require('http');

http.createServer(function (request, response) {
    console.log('New request @ ' + request.url);
    (function (response) {
         setTimeout(function () {
             console.log('Time is up');
             response.writeHead(200, {"Content-Type": "text/plain"});
             response.end('Hello World\n');
         }, 3000);
     })(response);
}).listen(8124);

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

But, the code above perform like a synchronous single thread app, which can only handle one request per 3 seconds.

I thought everything in node.js should act asynchronously. So, what's the problem here?

Upvotes: 5

Views: 6982

Answers (3)

user3238692
user3238692

Reputation: 87

var async,
__slice = [].slice;

async = require("async");

async.setTimeOut = function() {
    var arg, args, callback, delay, runWithTimeOut;
    callback = arguments[0], delay = arguments[1], arg = arguments[2], args = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
    runWithTimeOut = function() {
        return setTimeout(callback, delay, arg, args);
    };

    return async.parallel([runWithTimeOut]);
};

Upvotes: -3

balazs
balazs

Reputation: 5788

The SetTimeout is async, you don't need that anonym function in the middle, just write this.

var http = require('http');

http.createServer(function (request, response) {
  console.log('New request @ ' + request.url);
  setTimeout(function () {
    console.log('Time is up');
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end('Hello World\n');
  }, 3000);
}).listen(8124);

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

If you produce 10 concurent request the total comp time will be around 3sec, which means it is async. You can use the ab tool to check, or if you program node, maybe easier to install http-perf. and run nperf -c 10 -n 10 http://127.0.0.1:8124

Upvotes: 8

Marcus Granstr&#246;m
Marcus Granstr&#246;m

Reputation: 17974

You need to run your sleep in a new process. There is a module that can help you (https://github.com/cramforce/node-worker) or you can look at the normal api documentaion about spawn.

Upvotes: 0

Related Questions