title: How to continuously animate between 4 frames
body: <p>I'm trying to make a platforming game and need to animate between 4 frames. I have some code but that creates erratic animation. Here's my player object:</p>
  
  <pre><code>  var player = {};
    player.x = 0;
    player.y = 0;
    player.vx = 0;
    player.vy = 0;
    player.facing = "";
    player.jumping = false;
    player.shooting = false;
    player.animating = true;
    player.animationSpeed = 100;
    player.frame = 0;
    player.img = new Image();
    player.src = null;
    //I edited out the frames for length issues. They are player.frame0 through player.frame31
    player.physics = function() {
      document.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == 37) {
          player.vx -= player.vx;
          player.vx -= 3;
          player.facing = "left";
          player.animating = true;
        } else if (e.keyCode == 38) {
          player.vy -= player.vy;
          player.vy -= 10;
          player.jumping = true;
          player.animating = true;
        } else if (e.keyCode == 39) {
          player.vx -= player.vx;
          player.vx += 3;
          player.facing = "right";
          player.animating = true;
        } else if (e.keyCode == 32) {
          player.shooting = true;
          player.animating = true;
        }
      }
      document.onkeyup = function() {
        player.animating = false;
        player.jumping = false;
        player.vx = 0;
        player.vy = 0;
      }
      if (player.facing.toLowerCase() === "right" &amp;&amp; player.animating === true) {
        setInterval(function() {
          player.src = player.frame0;
          setTimeout(function() {
            player.src = player.frame1;
            setTimeout(function() {
              player.src = player.frame2;
              setTimeout(function() {
                player.src = player.frame3;
              },player.animationSpeed);
            },player.animationSpeed);
          },player.animationSpeed);
        },player.animationSpeed);
      }
      drawImg(player,player.x,player.y);
    }
  </code></pre>
  
  <p>Is there a better way to do this? The player.physics() method is where my animation code is. It's unfinished because I can't animate the frames.</p>