Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use setTimeout asynchronously in node.js

Tags:

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?

like image 377
Jack Avatar asked Dec 20 '12 11:12

Jack


People also ask

Is setTimeout asynchronous in node JS?

setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.

Can I use async in setTimeout?

setTimeout — new way: js development team, we are now able to use async/await syntax while dealing with setTimeout() functions. This feature was initially implemented in Node v.

Can I use setTimeout in node JS?

setTimeout() can be used to schedule code execution after a designated amount of milliseconds. This function is similar to window. setTimeout() from the browser JavaScript API, however a string of code cannot be passed to be executed.

How do I use async await inside setTimeout?

This can be solved with an async function: const delay = (duration) => new Promise(resolve => setTimeout(resolve, duration)); const asyncFunc = async (... args) => { await delay(1000); return computeResult(... args); };


1 Answers

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

like image 109
balazs Avatar answered Oct 13 '22 19:10

balazs