Node.js http.ClientRequest.setTimeout() Method

Last Updated : 27 Jan, 2023

The http.ClientRequest.setTimeout() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the request time out for the client request.

Syntax:

request.setTimeout(timeout[, callback])

Parameters: This method takes the time out value as a parameter in milliseconds, and the second parameter is the callback function that executes after the given timeout value.

Return Value: This method returns nothing but a callback function for further operation.

Example 1: Filename-index.js

JavaScript
// Node.js program to demonstrate the  
// request.setTimeout() method

// Importing http module
const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('okay');
});

// Now that server is running
server.listen(3000, '127.0.0.1', () => {

    // Make a request
    const options = {
        port: 3000,
        host: '127.0.0.1',
        headers: {
            'Connection': 'Upgrade',
            'Upgrade': 'websocket'
        }
    };

    // Getting client request
    const req = http.request(options);

    // Setting the timeout for the client request
    // by using setTimeout method
    req.setTimeout(3000, () => {
        console.log("timeout")
        process.exit(0)
    })
});

 
 Run the index.js file using the following command:

node index.js

Output:

timeout

Example 2: Filename-index.js

JavaScript
// Node.js program to demonstrate the  
// request.setTimeout() method

// Importing http module
const http = require('http');

// Create an HTTP server
http.createServer((req, res) => { }).listen(3000, '127.0.0.1', () => {

    // Getting client request
    const req = http.request({
        port: 3000,
        host: '127.0.0.1',
    });

    // Setting the timeout for the client request
    // by using setTimeout method
    req.setTimeout(5000, () => {
        console.log("timeout")
        process.exit(0)
    })
});

Run the index.js file using the following command:

node index.js

Output:

timeout

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_settimeout_timeout_callback

Comment

Explore