JavaScript Closures and setTimeout

后端 未结 2 553
长发绾君心
长发绾君心 2021-01-20 02:33

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 03:08

    The thing is that you're incrementing a timeIncrement inside closure. So effectively you do not increment it at all until first timeout happens. Here is the changed code:

    for(i=0;i<=counter;i++){
        setTimeout(function (){
            myDiv.style.width = wIncrement+"px"
            wIncrement++;
        }, i*1000);
    }
    

    You still might have issues with wIncrement variable. Also I would use setInterval instead of setTimeout for this reason.

提交回复
热议问题