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
const http = require( 'http' );
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type' : 'text/plain' });
res.end( 'okay' );
});
server.listen(3000, '127.0.0.1' , () => {
const options = {
port: 3000,
host: '127.0.0.1' ,
headers: {
'Connection' : 'Upgrade' ,
'Upgrade' : 'websocket'
}
};
const req = http.request(options);
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
const http = require( 'http' );
http.createServer((req, res) => { }).listen(3000, '127.0.0.1' , () => {
const req = http.request({
port: 3000,
host: '127.0.0.1' ,
});
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...