Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between req.setTimeout & socket.setTimeout?

I have two options to set a timeout to my http request. I am not sure about their difference.

First one is:

req.setTimeout(2000,function () {
  req.abort();
  console.log("timeout");
  self.emit('pass',message);
});

Second one is:

req.on('socket', function (socket) {
  socket.setTimeout(2000);  
  socket.on('timeout', function() {
      req.abort();
      self.emit('pass',message);
  });
}
like image 407
egiray Avatar asked Feb 06 '13 10:02

egiray


People also ask

Is setTimeout an API?

Executing setTimeout actually calls out to code that is not part of JS. It's part of a Web API which the browser provides for us. There are a different set of APIs like this available in node. setTimeout is then finished executing, while the Web API waits for the requested amount of time (1000ms).

What is the use of setTimeout?

The JavaScript setTimeout() method is a built-in method that allows you to time the execution of a certain function . You need to pass the amount of time to wait for in milliseconds , which means to wait for one second, you need to pass one thousand milliseconds .

What does setTimeout do 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.

Is there a limit to setTimeout?

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.


1 Answers

socket.setTimeout sets the timeout for the socket, e.g. to implement HTTP Keep-Alive.

request.setTimeout does internally call socket.setTimeout, as soon as a socket has been assigned to the request and has been connected. This is described in the documentation.

Hence, it's no difference, and you can choose which way to go. Of course, if you already have a request in your hands, you'd stick to the request's setTimeout function instead of digging for the underlying socket.

like image 161
Golo Roden Avatar answered Sep 22 '22 19:09

Golo Roden