JS Spritesheet Animation

HTML

<div id="cat"></div>

CSS

body {
    margin: 0;
}
#cat {
    width: 512px;
    height: 256px;
    background-image: 
    url("http://courses.mansion.fm/photo-5345/files/2014/03/runningcat.png");
    background-position: -512px 0px;
}

JavaScript

var lastRun = new Date().getTime();
var delay = 100; //milliseconds
var frame = 0;
var animating = false;

//keep track of each frame's background position using an array
frames = [
    [0,0]
    [-512, 0],
    [0, -256],
    [-512, -256],
    [0, -512],
    [-512, -512],
    [0, -768],
    [-512, -768]
    ];

function animate() {
    
   var now = new Date().getTime();
    
   //check if time difference since last run is over our delay time
   if(now - lastRun > delay) {
       
       //get the sprite's baground position based on the current frame
       var bgPos = frames[frame][0] + 'px ' + frames[frame][1] + 'px';
       
       //update the background position, this is what creates the animation
       $('#cat').css('background-position', bgPos);
       
       //update to the next frame
       frame++;
       
       //ensure we don't go out of range (we only have 8 frames)
       if(frame >= frames.length) {
           frame = 0;   
       }
       
       //update the last run time
       lastRun = now;
   }
    
    //recursively call requestAnimationFrame to continue looping
    requestAnimationFrame(animate);
}


/*
NOTE: 
Calling requestAnimationFrame tells the browser to call a specified animation function before the next repaint. In this case we call the function "animate"
*/

//initial call to requestAnimationFrame to start draw loop
requestAnimationFrame(animate);