Skip to content Skip to sidebar Skip to footer

Javascript Settimeout, Loops And Closure

The following code has me confused. My goal is to fade an HTML element from one opacity level to another, over a period of time. Below is my dimScreen() method, used to create a

Solution 1:

It's too late and still too hot to think much here right now. (2.30am, 28°C) Forgive me if my explanation falls short of expectations.

Basically, because you construct text strings to pass to setTimeout, each call gets the correct value for i. Since to pass an actual element, you can't use the string trick, you end up using the same value of i for each call to setOpacity.

As your question title indicates you understand, you need to use closures to get it to work right. I can't find(only followed 2 or 3 links) a good tute/S.O question that explains it in a way that seems relevant and clear.

Hope the code will be of use.

var overlay;
functiondimScreen()
{
   if(!overlay)
   {
      overlay = document.createElement('div');
      overlay.setAttribute('id', 'overlay');
      overlay.style.width = '100%';
      overlay.style.height = '100%';
      overlay.style.zindex = '1000';
      overlay.style.background = '#000013';
      overlay.style.position = 'fixed';
      overlay.style.left = '0';
      overlay.style.top = '0';
      overlay.style.opacity = '.0';

      document.body.appendChild(overlay);
      myFade(overlay, 0, 75, 2000);
   }
}
functionmyFade(element, startOpacity, stopOpacity, duration)
{
   var speed = Math.round(duration / 100);
   var timer = 0;
   if (startOpacity < stopOpacity)
   {     // fade infor (var i=startOpacity; i<=stopOpacity; i++)
      {
        (
            function()
            {
                var myI = i;
                setTimeout(function(){mySetOpacity(element,myI)}, timer * speed);
            }
        )()
         timer++;
      }
   }

   elsefor (var i=startOpacity; i>=stopOpacity; i--)
   {     // fade outfor (var i=startOpacity; i<=stopOpacity; i++)
      {
        (
            function()
            {
                var myI = i;
                setTimeout(function(){mySetOpacity(element,myI)}, timer * speed);
            }
        )()
         timer++;
      }
   }
}

functionmySetOpacity(el, opacityLevel)
{
   var eStyle = el.style;
   eStyle.opacity = opacityLevel / 100;
   eStyle.filter = 'alpha(opacity='+opacityLevel+')';
}

Post a Comment for "Javascript Settimeout, Loops And Closure"