Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save john-doherty/59dfc42f747f4aaaf97dedf86df31acb to your computer and use it in GitHub Desktop.
Save john-doherty/59dfc42f747f4aaaf97dedf86df31acb to your computer and use it in GitHub Desktop.
JavaScript window.setTimeout replacement using requestAnimationFrame for better performance
(function (window) {
'use strict';
var oldSetTimeout = window.setTimeout;
/**
* Behaves the same as setTimeout but uses requestAnimationFrame() for better performance
* @param {function} fn The callback function
* @param {int} delay The delay in milliseconds
* @return {object} ref to timeout function
*/
var setTimeoutOverride = function (fn, delay) {
var start = new Date().getTime();
var handle = {};
// allow setTimeout 0 to use original code, here is why that's important https://stackoverflow.com/a/33963453/443431
if (delay === 0) return oldSetTimeout(fn, delay);
function loop() {
var current = new Date().getTime();
var delta = current - start;
if (delta >= delay) {
fn.call();
}
else {
handle.value = requestAnimationFrame(loop);
}
}
handle.value = requestAnimationFrame(loop);
return handle;
};
/**
* Behaves the same as clearTimeout but uses cancelRequestAnimationFrame() for better performance
* @param {int|object} handle - ref returned from overridden setTimeout
* @returns {void}
*/
window.clearTimeout = function(handle) {
window.cancelAnimationFrame(handle.value);
};
// override
window.setTimeout = setTimeoutOverride;
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment