Created
July 24, 2013 18:16
-
-
Save artsyca/6073055 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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