Friday, May 21, 2010

setTimeout vs setInterval

setTimeout() is apparently WAY faster than using setInterval()

In Firefox I'm getting a limit of 14 FPS using setInterval(), but with setTimeout() my frame rate is 88 FPS!

Code example here:

 var fps;
 var startTime;
 var diffTime;
 var rate = 10;
 var frames = 0;
   
 function countTimeRecursive() {
  time  = new Date().getTime();
  diffTime = (time - startTime);
  frames++;
  if (diffTime >= 1000) {
   fps.textContent = "FPS: " + frames;
   frames = 0;
   diffTime = 0;
   startTime = time;
  }
  setTimeout('countTimeRecursive()', rate); 
 }
    
 function countTime() {
  time  = new Date().getTime();
  diffTime += (time - startTime);
  frames++;
  if (diffTime >= 1000) {
   fps.textContent = "FPS: " + frames;
   frames = 0;
   diffTime = 0;
   startTime = time;
  }
 }

 function countInterval() {
  setInterval('countTime()', rate);
 }
  
 window.onload = function() {
  // print and move them around
  // countTimeRecursive()
  countTimeRecursive();
  fps = document.getElementById('fps');
  startTime = new Date().getTime();
  diffTime = 0;
 } 


No comments:

Post a Comment