Created
April 24, 2018 17:54
-
-
Save john-doherty/59dfc42f747f4aaaf97dedf86df31acb to your computer and use it in GitHub Desktop.
JavaScript window.setTimeout replacement using requestAnimationFrame for better performance
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 (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