Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Forked from joelambert/README
Last active July 12, 2024 23:26
Show Gist options
  • Select an option

  • Save joyrexus/7304146 to your computer and use it in GitHub Desktop.

Select an option

Save joyrexus/7304146 to your computer and use it in GitHub Desktop.
RAF replacements for setTimeout and setInterval
Drop in replace functions for setTimeout() & setInterval() that
make use of requestAnimationFrame() for performance where available
http://www.joelambert.co.uk
Copyright 2011, Joe Lambert. All rights reserved
Free to use under the MIT license.
http://www.opensource.org/licenses/mit-license.php
// requestAnimationFrame() shim by Paul Irish
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
/**
* Behaves the same as setTimeout except uses requestAnimationFrame() where possible for better performance
* @param {function} fn The callback function
* @param {int} delay The delay in milliseconds
*/
window.requestTimeout = function(fn, delay) {
if( !window.requestAnimationFrame &&
!window.webkitRequestAnimationFrame &&
!window.mozRequestAnimationFrame &&
!window.oRequestAnimationFrame &&
!window.msRequestAnimationFrame)
return window.setTimeout(fn, delay);
var start = new Date().getTime();
(function loop(){
var current = new Date().getTime(),
delta = current - start;
delta >= delay ? fn.call() : requestAnimFrame(loop);
})();
};
/**
* Behaves the same as setInterval except uses requestAnimationFrame() where possible for better performance
* @param {function} fn The callback function
* @param {int} delay The delay in milliseconds
*/
window.requestInterval = function(fn, delay) {
if( !window.requestAnimationFrame &&
!window.webkitRequestAnimationFrame &&
!window.mozRequestAnimationFrame &&
!window.oRequestAnimationFrame &&
!window.msRequestAnimationFrame)
return window.setInterval(fn, delay);
var start = new Date().getTime();
(function loop() {
var current = new Date().getTime(),
delta = current - start;
if(delta >= delay) {
fn.call();
start = new Date().getTime();
}
requestAnimFrame(loop);
})();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment