Node.js http.ServerResponse.setTimeout() Method
Last Updated :
06 Apr, 2023
The httpServerResponse.setTimeout is an inbuilt application programming interface of class ServerResponse within the HTTP module which is used to set the Socket’s timeout value to msecs (Milliseconds).
Syntax:
const response.setTimeout(msecs[, callback])
Parameters: This method takes the first parameter as socket time-out value in a millisecond, and the second parameter is a callback function which is optional.
Return Value: This method returns nothing but a call-back function for further operation.
Example 1: Filename-index.js
Javascript
const http = require( 'http' );
const PORT = process.env.PORT || 3000;
const httpServer = http.createServer(
function (request, response) {
response.setTimeout(6000, () => {
console.log( "socket is destroyed due to timeout" )
})
});
httpServer.listen(PORT, () => {
console.log( "Server is running at port 3000..." );
});
|
Run the index.js file using the following command:
node index.js
Output:
Server is running at port 3000...
socket is destroyed due to timeout
Now open your browser and go to http://localhost:3000/, you will see the following output:
ERR_CONNECTION_REFUSED
Example 2: Filename-index.js
Javascript
const http = require( 'http' );
const httpHandlers = (request, response) => {
response.setTimeout(5000, () => {
console.log( "socket is destroyed due to timeout" )
})
}
const httpServer = http.createServer(
httpHandlers).listen(3000, () => {
console.log( "Server is running at port 3000..." );
});
|
Run the index.js file using the following command:
node index.js
Output:
Server is running at port 3000...
socket is destroyed due to timeout
Now open your browser and go to http://localhost:3000/, you will see the following output:
ERR_CONNECTION_REFUSED
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_settimeout_msecs_callback
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...