-2
function fade90() { document.getElementById("myDiv").style.opacity="0.90"; setTimeout("fade80()", 100); }
function fade80() { document.getElementById("myDiv").style.opacity="0.80"; setTimeout("fade70()", 100); }
function fade70() { document.getElementById("myDiv").style.opacity="0.70"; setTimeout("fade60()", 100); }
function fade60() { document.getElementById("myDiv").style.opacity="0.60"; setTimeout("fade50()", 100); }
function fade50() { document.getElementById("myDiv").style.opacity="0.50"; setTimeout("fade40()", 100); }
function fade40() { document.getElementById("myDiv").style.opacity="0.40"; setTimeout("fade30()", 100); }
function fade30() { document.getElementById("myDiv").style.opacity="0.30"; setTimeout("fade20()", 100); }
function fade20() { document.getElementById("myDiv").style.opacity="0.20"; setTimeout("fade10()", 100); }
function fade10() { document.getElementById("myDiv").style.opacity="0.10"; setTimeout("hide()", 100); }

I write this. Is this correct? If not please fix this.

function cls_msg(){
for (i=1;i<10;i++)
{
setTimeout(document.getElementById("myDiv").style.opacity=100-(i*10), 100);
}

Thanks

tranzme
  • 3
  • 1

1 Answers1

1

You probably want this :

var elem = document.getElementById("myDiv");
for (i=1;i<10;i++) {
   (function(i){
      setTimeout(
        function(){elem.style.opacity=100-(i*10)},
        (i+1)*100
      );
   })(i);
}

Differences with your code :

  • timeouts are different so that they're not called all at the same time (the code doesn't pause until the next timeout is executed)
  • i is protected by a closure so that it doesn't have the value of end of loop when the timeouts are fired
  • the first argument passed to setTimeout is a function
  • as suggered by yabol, the element is cached
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 2
    It will be better for performance to keep `document.getElementById("myDiv")` outside the loop in variable. Of course this is only if #myDiv element not gonna change. – Jan.J Mar 04 '13 at 20:30
  • @yabol Yes, that's better. It doesn't really matter for performances (`getElementById` is very fast) but that's evidently a good habit. – Denys Séguret Mar 04 '13 at 20:32
  • Yep, I know it is fast, but in case author wanna change element selection to something more time consuming ;) – Jan.J Mar 04 '13 at 20:34