Skip to content

Instantly share code, notes, and snippets.

@dwelch2344
Created February 28, 2013 21:44
Show Gist options
  • Select an option

  • Save dwelch2344/5060372 to your computer and use it in GitHub Desktop.

Select an option

Save dwelch2344/5060372 to your computer and use it in GitHub Desktop.
Throttling function, abstracted from Underscore
var throttle = function (func, wait) {
var context, args, timeout, result;
var previous = 0;
var later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date();
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, throttle(function () { // limit to once every 500ms
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
}, 500));
}
// ...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment