Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added request.setTimeout support #80

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,12 @@ Request.prototype.end = function (s) {
}
};

Request.prototype.setTimeout = function(msecs, callback) {
if (callback) this.once('timeout', callback);
this.xhr.ontimeout = this.emit.bind(this, 'timeout');
this.xhr.timeout = msecs;
};

// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html
Request.unsafeHeaders = [
"accept-charset",
Expand Down
52 changes: 52 additions & 0 deletions test/request_url.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,55 @@ test('Test POST XHR2 types', function(t) {
};
request.end(new global.FormData());
});

test('Test setTimeout sets xhr timeout and ontimeout', function(t) {
var url = '/api/foo';
var request = http.request({ url: url, method: 'POST' }, noop);

request.setTimeout( 999, function(){});

t.equal( request.xhr.timeout, 999);
t.ok( request.xhr.ontimeout, 'Make sure ontimeout is a function');
t.end();
});


test('Test setTimeout will execute callback after timeout', function(t) {
var url = '/api/foo';
var request = http.request({ url: url, method: 'POST' }, noop);
var abortSend;

t.plan(1);

// send query handler function
var onSend = function (data) {
t.fail('setTimeout should have cancelled the request');
};

// timeout callback function
var onTimeout = function(){
clearTimeout( abortSend);
t.pass('timeout called');
};

// simulate a slow-executing query
request.xhr.send = function( data) {

// execute the query after a delay
abortSend = setTimeout(
onSend.bind( this, data), 1000
);

// simulate xhr ontimeout, normally this
// gets done somewhere in the browser
if (this.timeout && this.ontimeout) {
setTimeout( this.ontimeout, this.timeout);
}
}

// setup a timeout that will abort before query fires
request.setTimeout( 200, onTimeout);
request.end();
});