Node. js timeout _ node. js-js tutorial

Source: Internet
Author: User
This article introduces the timeout event in nodejs, and provides a detailed example analysis, which is very detailed, if the server does not respond within the specified time period (it may be due to a problem with the connection between networks, it may also be because the server fails or the network firewall blocks the connection between the client and the server), the response times out, And the http. timeout event of the ServerResponse object.

Response. setTimeout (time, [callback]);

You can also not specify the callback function in setTimeout. You can use the time listening method to specify the callback function.

If no time-out callback function is specified, the socket port connected to the http client is automatically closed when the time-out occurs. if a time-out callback function is specified, a callback function is called and the socket port connected to the http client is not automatically closed.

The Code is as follows:


Var http = require ("http ");
Var server = http. createServer (function (req, res ){
If (req. url! = "/Favicon. ico "){
// Timeout listener
/* Res. setTimeout (1000 );
Res. on ("timeout", function (){
Console. log ("response timeout .");
});*/
// Direct callback upon timeout
Res. setTimeout (1000, function (){
Console. log ("response timeout .");
});
SetTimeout (function (){
Res. setHeader ("Content-Type", "text/html ");
Res. write (" ");
Res. write ("hello ");
Res. end ();
},2000 );
}
});
Server. listen (1337, "localhost", function (){
Console. log ("Start listening" + server. address (). port + "......");
});

Running code result:

After deleting the expired callback function:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.