Skip to content

Instantly share code, notes, and snippets.

@sinslav
Created December 30, 2015 16:32
Show Gist options
  • Save sinslav/c3a8108ef9e3274d8e58 to your computer and use it in GitHub Desktop.
Save sinslav/c3a8108ef9e3274d8e58 to your computer and use it in GitHub Desktop.
js
function throttle(func, ms) {
var isThrottled = false,
savedArgs,
savedThis;
function wrapper() {
if (isThrottled) { // (2)
savedArgs = arguments;
savedThis = this;
return;
}
func.apply(this, arguments); // (1)
isThrottled = true;
setTimeout(function() {
isThrottled = false; // (3)
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
}
# same on CoffeeScript
throttle = (func, ms) ->
isThrottled = false
savedArgs = undefined
savedThis = undefined
wrapper = ->
if isThrottled
# (2)
savedArgs = arguments
savedThis = this
return
func.apply this, arguments
# (1)
isThrottled = true
setTimeout (->
isThrottled = false
# (3)
if savedArgs
wrapper.apply savedThis, savedArgs
savedArgs = savedThis = null
return
), ms
return
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment