requestAnimationFrame EXAMPLE

Looking for a way to prevent animations from firing when multiple tabs are open. Inspired by previous work from Paul Irish and Erik Möller.

by bcmoney

HTML

<a id="start" href="#start">Start</a> | <a id="stop" href="#stop">Stop</a>
<div id="container">
    <div id="animated">Animated content</div>
</div>

CSS

body {
    overflow:hidden;
}
#container {    
    width:100%;
    height:100%;
}
#animated { 
    width: 120px;
    position: absolute;
    left: 2px;
    top: 20px;
    padding: 50px;
    background: limegreen;
    color: white
}

JavaScript

var animation = 1;
var elem = document.getElementById("animated");
var startTime = undefined;
var AVAILABLE_WIDTH = $("#container").width() || width;
 
// requestAnimationFrame shim with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame || 
          window.oRequestAnimationFrame || 
          window.msRequestAnimationFrame || 
         /*
          * @param function FrameRequestCallback 
          * @param DOMElement Element
          */
          function(callback, element){
            window.setTimeout(callback, 1000/60);
          };
})();

// cancelAnimationFrame shim with clearTimeout fallback
window.cancelAnimFrame = (function(){
  return  window.cancelAnimationFrame ||
          window.webkitCancelAnimationFrame ||
          window.mozCancelAnimationFrame ||
          window.oCancelAnimationFrame ||
          window.msCancelAnimationFrame ||
         /*
          * @param function FrameRequestCallback
          * @param DOMElement Element
          */
          function(callback){
            window.clearTimeout(callback);
          };
})();


function scrollRight(time) {
  if (time === undefined) {
    time = +new Date;
  }
  if (startTime === undefined) {
    startTime = time; 
  }
  elem.style.left = ((time - startTime)/10 % AVAILABLE_WIDTH) + "px";
}

function animate(elem) {
  scrollRight();
  animation = requestAnimFrame(animate, elem);
}

function deanimate(fn, elem) {
  window.cancelAnimFrame(animation);
}


document.getElementById('start').onclick = function() {
  animate(elem);
};

document.getElementById('stop').onclick = function() {
  deanimate(elem);    
};