Created
January 30, 2018 18:31
-
-
Save dkozma/71aa985632e9235921159a2179486581 to your computer and use it in GitHub Desktop.
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
var wrapperFactory = function (wrapperContext) { | |
var resetCancelToken = function () { | |
wrapperContext.cancelToken = false; | |
}; | |
var wrapper = function (cbThis, cb) { | |
var args = []; | |
for (var _i = 2; _i < arguments.length; _i++) { | |
args[_i - 2] = arguments[_i]; | |
} | |
wrapperContext.callbackThis = cbThis; | |
wrapperContext.args = args; | |
if (wrapperContext.cancelToken) { | |
return; | |
} | |
if ('requestAnimationFrame' in window) { | |
wrapperContext.cancelToken = window.requestAnimationFrame(function () { | |
cb.apply(wrapperContext.callbackThis, wrapperContext.args); | |
resetCancelToken(); | |
}); | |
} | |
else { | |
cb.apply(wrapperContext.callbackThis, wrapperContext.args); | |
wrapperContext.cancelToken = window.setTimeout(resetCancelToken, 1000 / 60); // 60 fps | |
} | |
}; | |
wrapper.cancel = function () { | |
if ('requestAnimationFrame' in window) { | |
window.cancelAnimationFrame(wrapperContext.cancelToken); | |
} | |
window.clearTimeout(wrapperContext.cancelToken); | |
resetCancelToken(); | |
}; | |
return wrapper; | |
}; | |
var throttleFactory = function (callback, thisArg) { | |
var argArray = []; | |
for (var _i = 2; _i < arguments.length; _i++) { | |
argArray[_i - 2] = arguments[_i]; | |
} | |
var wrapper = wrapperFactory({}); | |
var argCount = arguments.length; | |
var throttledCallback = function () { | |
var args = []; | |
for (var _i = 0; _i < arguments.length; _i++) { | |
args[_i] = arguments[_i]; | |
} | |
wrapper.apply(void 0, [argCount > 1 ? thisArg : this, callback].concat(argArray, args)); | |
}; | |
throttledCallback.cancel = function () { return wrapper.cancel(); }; | |
return throttledCallback; | |
}; | |
/** | |
* Returns a throttled function which runs once per rendered frame using | |
* requestAnimationFrame. If window.requestAnimationFrame does not exist, | |
* the behavior will be approximated using setTimeout. | |
* | |
* @param callback the function to be throttled | |
*/ | |
window.throttle = function (callback) { | |
var throttledCallback = throttleFactory(callback); | |
// Override `bind()` to create a new throttled callback, otherwise both | |
// the unbound and bound callbacks will have the same scope. | |
throttledCallback.bind = throttleFactory.bind(null, callback); | |
return throttledCallback; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment