Skip to content

Instantly share code, notes, and snippets.

@bmcorser
Last active August 29, 2015 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmcorser/78396b80d441877d7921 to your computer and use it in GitHub Desktop.
Save bmcorser/78396b80d441877d7921 to your computer and use it in GitHub Desktop.
Throttle $.ajax calls
define(['jquery'], function ($) {
var THROTTLE = 200; // ms
var previousCalls = {}; // for namespaces
var throttle = function (name, ajaxOpts) {
var now = new Date();
previousCalls[name] = now;
var checkPreviousCalls = function () {
// has something else touched our namespace since timeout?
if (previousCalls[name] !== now) {
console.log('THROTTLE ' + ajaxOpts.url);
} else {
console.log('CALL ' + ajaxOpts.url);
$.ajax(ajaxOpts);
}
};
setTimeout(checkPreviousCalls, THROTTLE);
};
return throttle;
});
@bmcorser
Copy link
Author

Example usage:

require(['throttle'], function (throttle) {
  var ajaxOpts = {
    url: 'https://cors-test.appspot.com/test',
    success: function () { console.log('2 × THROTTLE, 1 × CALL. Amirite?') }
  }
  throttle('amirite?', ajaxOpts);
  throttle('amirite?', ajaxOpts);
  throttle('amirite?', ajaxOpts);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment