Skip to content

Instantly share code, notes, and snippets.

@andrewmp1
Created March 14, 2013 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewmp1/5157876 to your computer and use it in GitHub Desktop.
Save andrewmp1/5157876 to your computer and use it in GitHub Desktop.
var callMethod = function(target, method, args) {
if (Ember.typeOf(method) === 'string') {
method = target[method];
}
return method.apply(target, args);
};
/**
Returns a function, that, when invoked, will only be triggered at most once during a given window of time.
*/
Ember.throttle = function(target, method, wait) {
var timeout, throttling, more, result, whenDone;
if (Ember.typeOf(method) === 'number') {
wait = method;
method = target;
target = null;
}
whenDone = Ember.debounce(function() { more = throttling = false; }, wait);
return function() {
var later, args = arguments;
later = function() {
timeout = null;
if (more) { callMethod(target, method, args); }
whenDone();
};
if (!timeout) { timeout = setTimeout(later, wait); }
if (throttling) {
more = true;
} else {
result = callMethod(target, method, args);
}
whenDone();
throttling = true;
return result;
};
};
/**
Returns a function, that, as long as it continues to be invoked, will not be triggered.
The function will be called after it stops being called for N milliseconds.
If immediate is passed, trigger the function on the leading edge, instead of the trailing.
*/
Ember.debounce = function(target, method, wait, immediate) {
var timeout;
if (Ember.typeOf(method) === 'number') {
immediate = wait;
wait = method;
method = target;
target = null;
}
return function() {
var later, args = arguments;
later = function() {
timeout = null;
if (!immediate) { callMethod(target, method, args); }
};
if (immediate && !timeout) { callMethod(target, method, args); }
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment