Skip to content

Instantly share code, notes, and snippets.

@eduardo-matos
Last active December 25, 2015 14:59
Show Gist options
  • Save eduardo-matos/6995006 to your computer and use it in GitHub Desktop.
Save eduardo-matos/6995006 to your computer and use it in GitHub Desktop.
Delayed AJAX requests
define('delayable-xhr', [
'dojo/request/xhr',
'dojo/request/util',
'dojo/Deferred'
], function (
xhr,
util,
Deferred
) {
'use strict';
var delayableXhr = function(url, options) {
var canceler = function () {
window.clearTimeout(timeout);
xhrPromise && xhrPromise.cancel();
};
var def = new Deferred(canceler);
var xhrPromise;
var timeout;
if(!options || !options.delay) {
return xhr(url, options);
}
timeout = window.setTimeout(function () {
xhrPromise = xhr(url, options).then(function () {
def.resolve.apply(this, arguments);
}, function () {
def.reject.apply(this, arguments);
});
}, options.delay);
return def.promise;
}
// ".get", ".post", ".put" and ".del", just like regular xhr
util.addCommonMethods(delayableXhr);
return delayableXhr;
});
(function ($) {
'use strict';
$.delayableAjax = function (options) {
var args = arguments;
var def = $.Deferred();
var promise = def.promise();
var timeout;
var xhrPromise;
def.abort = promise.abort = function () {
window.clearTimeout(timeout);
xhrPromise && xhrPromise.abort();
};
if(args.length !== 1) {
return $.ajax.apply(this, args);
}
if(!options || !options.delay) {
return $.ajax(options);
}
timeout = window.setTimeout(function () {
xhrPromise = $.ajax(options).done(function () {
def.resolveWith(this, arguments);
}).fail(function () {
def.rejectWith(this, arguments);
});
}, options.delay);
return promise;
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment