Closures are something I still don’t fully grasp in JS. I think this is a closure issue. I’m trying to create a progress bar. Every x seconds I want to increment the width of a DIV. Here’s the part that is supposed to do that:
for(i=0;i<=counter;i++){
setTimeout(function (){
myDiv.style.width = wIncrement+"px"
timeIncrement++;
wIncrement++;
},timeIncrement*1000);
}
What I want to happen is every x seconds, increase the size of the bar. If course, that’s not what’s happening.
I’m pretty sure (hope) that this is a closure issue, but the syntax to mix with a setTimout completely flummoxes me. Can anyone help me grasp the concepts needed to fix the closure issue in this example?
The thing is that you’re incrementing a
timeIncrementinside closure. So effectively you do not increment it at all until first timeout happens. Here is the changed code:You still might have issues with
wIncrementvariable. Also I would usesetIntervalinstead ofsetTimeoutfor this reason.