requestAnimationFrame vs setInterval test
Test to check the performance differences between requestAnimationFrame and setInterval.
HTML
<div id="fps" style="background-color:white;border:1px dashed blue;text-align:center"></div>
CSS
div { height: 20px; background-color: crimson; margin:3px;}
JavaScript
/* Run Modes
0: setInterval 1
1: setInterval 60
2: setInterval 16
3: requestAnimationFrame
4: requestInterval 1
5: requestInterval 60
6: requestInterval 16
*/
var runMode = 1;
/*
* 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.
* 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 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.mozCancelRequestAnimationFrame) && // Firefox 5 ships without cancel support
!window.oRequestAnimationFrame &&
!window.msRequestAnimationFrame)
return window.setInterval(fn, delay);
var start = new Date().getTime(),
handle = new Object();
function loop() {
handle.value = requestAnimFrame(loop);
var current = new Date().getTime(),
delta = current - start;
if(delta >= delay) {
fn.call();
start = new Date().getTime();
}
};
handle.value = requestAnimFrame(loop);
return handle;
}
/**
* Behaves the same as clearInterval except uses cancelRequestAnimationFrame() where...