JavaScript Closures and setTimeout

点点圈 提交于 2019-12-02 00:03:38

问题


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?


回答1:


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.




回答2:


Instead of using setTimeout you want to use setInterval. The latter will call the function once per interval instead of just once.

var width = 50
setInternal(function () {
  myDiv.style.width = width
  width++
  }, timeIncrement * 1000);

Additionally at some point you'll probably want to end the interval and stop incrementing the size. For that you'll need to call clearInterval on the result of setInterval

var width = 50
var t = setInterval(function () {
  myDiv.style.width = width
  width++
  if (doneIncrementing) {
    clearInterval(t);
  }
  }, timeIncrement * 1000);


来源:https://stackoverflow.com/questions/5479604/javascript-closures-and-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!