Javascript setting timeout problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kong Chun Ho
    New Member
    • Jul 2010
    • 34

    Javascript setting timeout problem

    Hello,

    I have a problem on setting timeout in for loop.

    Here is my code:
    Code:
    function setOpacity (elem, val) {
    var z = document.getElementById(elem);
    z.style.opacity=val/100;
    z.style.filter = "alpha(opacity=" + val + ")";
    }
    function LiveSupport() {
    var x = document.getElementById('c_cover');
    var y = document.getElementById('c_popcontent');
    var z;
    var startOpacity = '0'; //int only
    var endOpacity = '70'; //int only
    var nowOpacity;
    var t = 0;
    x.style.position = 'absolute';
    x.style.top = '80px';
    x.style.left = '50%';
    x.style.marginLeft = '-325px';
    x.style.background = '#000';
    x.style.zIndex = '998';
    x.style.height = '676px';
    x.style.width = '650px';
    x.style.opacity=startOpacity/100;
    x.style.filter = "alpha(opacity=" + startOpacity + ")";
    for (z=startOpacity; z!=endOpacity; z++) {
    t++;
    setTimeout("setOpacity('c_cover', z);", t);
    }
    }
    When i run "LiveSupport(); ", i have received "z is not defined" error!

    How to fix it?

    Thanks
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    that’s right. "setOpacity('c_ cover', z);" is not executed in the scope of LiveSupport() but of setTimeout()/window. thus it is not defined. you would have to use a Closure for that.
    Code:
    // untested
    setTimeout(function(){ setOpacity('c_cover', z); }, t);

    Comment

    • Kong Chun Ho
      New Member
      • Jul 2010
      • 34

      #3
      ok thanks, it works!

      Comment

      Working...