Created
December 30, 2015 16:32
-
-
Save sinslav/c3a8108ef9e3274d8e58 to your computer and use it in GitHub Desktop.
js
This file contains 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
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