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);
});
}
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).
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With