Skip to content
Related Articles

Related Articles

Improve Article
Node.js http.ServerResponse.setTimeout() Method
  • Last Updated : 12 Jan, 2021

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




// Node.js program to demonstrate the  
// response.setTimeout() method
    
// Importing http module 
var http = require('http'); 
    
// Setting up PORT 
const PORT = process.env.PORT || 3000; 
    
// Creating http Server 
var httpServer = http.createServer(
  function(request, response) { 
  
  // Setting the socket time out value
  // by using setTimeout method
  response.setTimeout(6000,() => {
    console.log("socket is destroyed due to timeout")
  })
}); 
    
// Listening to http Server 
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




// Node.js program to demonstrate the  
// response.setTimeout() Method
    
// Importing http module 
var http = require('http'); 
  
// Request and response handler 
const httpHandlers = (request, response) => { 
    
  // Setting the socket time out value
  // by using setTimeout method
  response.setTimeout(5000,() => {
    console.log("socket is destroyed due to timeout")
  })
    
// Creating http Server 
var 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




My Personal Notes arrow_drop_up
Recommended Articles
Page :