Created
May 21, 2016 07:00
-
-
Save said-and-done/016b219dceb4813d687180d5b9c2cdef to your computer and use it in GitHub Desktop.
Call function at most once per every [wait] milliseconds. Useful for rate-limiting.
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
| window.addEventListener('resize', throttle(resizer, 200)); | |
| function throttle(func, wait) { | |
| // from underscore.js | |
| var _now = Date.now || function() { return new Date().getTime(); }, | |
| context, args, result, timeout = null, previous = 0; | |
| var later = function() { | |
| previous = _now(); | |
| timeout = null; | |
| result = func.apply(context, args); | |
| if (!timeout) context = args = null; | |
| }; | |
| return function() { | |
| var now = _now(), remaining = wait - (now - previous); | |
| context = this; | |
| args = arguments; | |
| if (remaining <= 0 || remaining > wait) { | |
| if (timeout) { | |
| clearTimeout(timeout); | |
| timeout = null; | |
| } | |
| previous = now; | |
| result = func.apply(context, args); | |
| if (!timeout) context = args = null; | |
| } else if (!timeout && options.trailing !== false) { | |
| timeout = setTimeout(later, remaining); | |
| } | |
| return result; | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment