You can try something like this:
function doRequest(url, callback) { var timer, req, sawResponse = false; req = http.get(url, callback) .on('error', function(err) { clearTimeout(timer); req.abort(); // prevent multiple execution of `callback` if error after // response if (!sawResponse) doRequest(url, callback); }).on('socket', function(sock) { timer = setTimeout(function() { req.abort(); doRequest(url, callback); }, 10000); }).once('response', function(res) { sawResponse = true; clearTimeout(timer); }); }
UPDATE: In recent / modern versions of node, you can now specify the timeout option (measured in milliseconds), which sets the socket timeout (before connecting the socket). For instance:
http.get({ host: 'example.org', path: '/foo', timeout: 5000 }, (res) => { // ... });
source share