title: Javascript time-based animation and requestAnimationFrame
body: <p>I have been playing around with <code>canvas</code> and animation, with HTML5 games in mind specifically and quickly learnt the limitations of just using <code>requestAnimationFrame (rFA)</code> and have moved to time-based animations.</p>
  
  <p>I want to maintain constant gameplay regardless of monitor refresh rate or FPS but am unsure how best to handle the animations. I have read through all sorts of implementations but have not found any best practice so to speak. Should I be using a combination of the two?</p>
  
  <p>So far I have considered several options:</p>
  
  <ul>
  <li><p><code>rFa</code> only (changes results when fps changes):</p>
  
  <pre><code>var animate = function() {
       draw();
       requestAnimationFrame(animate);
  }
  </code></pre></li>
  <li><p>time-based only (not always consistent):</p>
  
  <pre><code>var animate = function() {
      now = Date.now();
      delta = now - last;
      last = now;
  
      draw(delta);
      window.setTimeout(animate, 1000/60)
  }
  </code></pre></li>
  <li><p>set FPS on <code>rFA</code> with <code>setInterval</code> (not always consistent):</p>
  
  <pre><code>setInterval(function () {
      draw();
      requestAnimationFrame();
  }, 1000/fps);
  </code></pre></li>
  <li><p><code>rFA</code> trying to force fps (does not seem very robust, variable delta would work better):</p>
  
  <pre><code>var delta = 1000 / fps;
  var animate = function() {
     now = Date.now();
     if (now - last &gt;= delta) {
         last = now;
      }
  
      draw(delta);
      requestAnimationFrame(animate);
  }
  </code></pre></li>
  <li><p>time-based <code>rFA</code> (some strange results):</p>
  
  <pre><code>var animate = function () {
      now = Date.now();
      delta = now - last;
      last = now;
  
      draw(delta);
      requestAnimationFrame(animate);
  }
  </code></pre></li>
  </ul>
  
  <p>Ignore the lack of browser support and the use of Date.now(), I just want to demonstrate my flow of thinking. I think that the last option is preferable, but the last two can run into problems with updating too far and missing collisions etc as well as updates taking too long that the animation looses all control.</p>
  
  <p>Also when a user tabs out using <code>rFA</code> only the animation will pause, using a time based function to call <code>rFA</code> means that the game/animation will continue to run in the background which is not ideal.</p>
  
  <p>What would be the best way to handle animations trying to keep consistent results regardless of fps, all of the above might be bad and my apologies for the long post (it is just what I have tried so far and am still pretty lost)? even better with with the above issues in mind?</p>