0

I have implemented the following code for fade in by changing the opacity value, which is working so far, but not sure why we need the curOpacity to hold the value outside,

working code

for(let i=0;i<squares.length;i++) {
        var curOpacity = 0;

        (function(index){
            setInterval(function(){
                curOpacity += 0.1;
                squares[index].style.opacity = curOpacity;
            }, 200)
        })(i);
    }

I did not use curOpacity variable at 1st time, and it is not working, could you please tell me the reason and which topic related to that?

Not working code,

for(let i=0;i<squares.length;i++) {
    (function(index){
        setInterval(function(){
            squares[index].style.opacity += 0.1;
        }, 200)
    })(i);
}
Ziiiijun
  • 3
  • 2
  • Possible duplicate of [setTimeout with Loop in JavaScript](https://stackoverflow.com/questions/19221690/settimeout-with-loop-in-javascript) – Dan O Apr 26 '19 at 22:55
  • there are many questions on Stack Overflow regarding `for` loops and `setTimeout` together in javascript. which have you tried, why didn't they work, and what makes your particular question unique? – Dan O Apr 26 '19 at 22:56

1 Answers1

2

squares[index].style.opacity is a string. Convert it to a number before trying to do math at it:

squares[index].style.opacity = +squares[index].style.opacity + 0.1;
AuxTaco
  • 4,883
  • 1
  • 12
  • 27