Last active
October 19, 2018 22:32
-
-
Save hectorguo/0d2bb3e54a113c6bdf1a136e6099e22e to your computer and use it in GitHub Desktop.
setInterval advanced version (using requestAnimationFrame to improve performance)
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
// requestAnimationFrame Polyfill for IE9 | |
(function() { | |
var lastTime = 0; | |
var vendors = ['ms', 'moz', 'webkit', 'o']; | |
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { | |
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; | |
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] | |
|| window[vendors[x]+'CancelRequestAnimationFrame']; | |
} | |
if (!window.requestAnimationFrame) | |
window.requestAnimationFrame = function(callback, element) { | |
var currTime = Date.now(); | |
var timeToCall = Math.max(0, 16 - (currTime - lastTime)); | |
var id = window.setTimeout(function() { callback(currTime + timeToCall); }, | |
timeToCall); | |
lastTime = currTime + timeToCall; | |
return id; | |
}; | |
if (!window.cancelAnimationFrame) | |
window.cancelAnimationFrame = function(id) { | |
clearTimeout(id); | |
}; | |
}()); | |
// window.performance.now() Polyfill for IE9 | |
(function() { | |
if ('performance' in window == false) { | |
window.performance = {}; | |
} | |
if ('now' in window.performance == false) { | |
window.performance.now = function now(){ | |
return Date.now(); | |
} | |
} | |
}()); | |
// leverage requestAnimationFrame to replace setInterval for performance | |
function setIntervalEx(fn, delay) { | |
var start = window.performance.now(), | |
handle = {}; // save current requestAnimationFrame id | |
function loop(current) { | |
var delta = current - start; | |
if (delta >= delay) { | |
fn.call(); | |
// return; // will be changed to setTimeout if return at this line. | |
start = window.performance.now(); | |
} | |
handle.id = requestAnimationFrame(loop); | |
} | |
handle.id = requestAnimationFrame(loop); | |
return handle; | |
} | |
function clearIntervalEx(handle) { | |
handle && cancelAnimationFrame(handle.id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment