title: JavaScript setTimeout() slows down under heavy load
body: <p>I've created a script that fades the background color of an element. I use setTimeout() to make an incremental change to the color every 5 ms. The script works great if I'm just fading the background color of one thing at a time, but if I've got, say, 50 elements I'm all fading at once, the speed is much slower than 5 ms because of all the concurrent setTimeout()s running at once. A fade that normally should execute in 1 second, for example, may take 30 seconds if I'm fading 50 elements at once.</p>
  
  <p>Any ideas how I can overcome this?</p>
  
  <p>Here's the script in case anyone has an ideas:</p>
  
  <pre><code>function fadeBackground(elementId, start, end, time) {
      var iterations = Math.round(time / 5);
  
      var step = new Array(3);
  
      step[0] = (end[0] - start[0]) / iterations;
      step[1] = (end[1] - start[1]) / iterations;
      step[2] = (end[2] - start[2]) / iterations;
  
      stepFade(elementId, start, step, end, iterations);
  }
  
  function stepFade(elementId, cur, step, end, iterationsLeft) {
      iterationsLeft--;
  
      document.getElementById(elementId).style.backgroundColor
          = "rgb(" + cur[0] + "," + cur[1] + "," + cur[2] + ")";
  
      cur[0] = Math.round(end[0] - step[0] * iterationsLeft);
      cur[1] = Math.round(end[1] - step[1] * iterationsLeft);
      cur[2] = Math.round(end[2] - step[2] * iterationsLeft);
  
      if (iterationsLeft &gt; 1) {
          setTimeout(function() {
              stepFade(elementId, cur, step, end, iterationsLeft);
          }, 5);
      }
      else {
          document.getElementById(elementId).style.backgroundColor 
              = "rgb(" + end[0] + "," + end[1] + "," + end[2] + ")";
      }
  }
  </code></pre>
  
  <p>It's used like this:</p>
  
  <pre><code>fadeBackground("myList", [98,180,232], [255,255,255], 1000);
  </code></pre>