title: Javascript: how to pass different object to setTimeout handlers created in a loop?
body: <p>I'm trying to write some JS replicating jQuery's fadeIn and fadeOut functions. Here's the code I have so far:</p>
  
  <pre><code>function fadeIn(elem, d, callback)
  {
  
      var duration = d || 1000;
      var steps = Math.floor(duration / 50);
      setOpacity(elem,0);
      elem.style.display = '';
      for (var i = 1; i &lt;= steps; i++)
      {
          console.log(i/steps + ', ' + (i/steps) * duration);
          setTimeout('setOpacity("elem", '+(i / steps)+' )', (i/steps) * duration);
      }
      if (callback)
          setTimeout(callback,d);
  }
  function setOpacity(elem, level)
  {
      console.log(elem);
      return;
      elem.style.opacity = level;
      elem.style.MozOpacity = level;
      elem.style.KhtmlOpacity = level;
      elem.style.filter = "alpha(opacity=" + (level * 100) + ");";
  }
  </code></pre>
  
  <p>I'm having troubles with the first setTimeout call - I need to pass the object 'elem' (which is a DOM element) to the function setOpacity. Passing the 'level' variable works just fine... however, I'm getting "elem is not defined" errors. I think that's because by the time any of the setOpacity calls actually run, the initial fadeIn function has finished and so the variable elem no longer exists.</p>
  
  <p>To mitigate this, I tried another approach:</p>
  
  <pre><code>setTimeout(function() { setOpacity(elem, (i / steps));}, (i/steps) * duration);
  </code></pre>
  
  <p>The trouble now is that when the function is called, (i/steps) is now always 1.05 instead of incrementing from 0 to 1.</p>
  
  <p>How can I pass the object in question to setOpacity while properly stepping up the opacity level?</p>