JavaScript 闭包和 setTimeout
闭包是我在 JS 中还没有完全掌握的东西。我认为这是一个封闭问题。我正在尝试创建一个进度条。每隔 x 秒我想增加 DIV 的宽度。这是应该执行此操作的部分:
for(i=0;i<=counter;i++){
setTimeout(function (){
myDiv.style.width = wIncrement+"px"
timeIncrement++;
wIncrement++;
},timeIncrement*1000);
}
我想要发生的是每 x 秒增加条形的大小。当然,如果事实并非如此。
我很确定(希望)这是一个闭包问题,但是与 setTimout 混合的语法完全让我感到困惑。谁能帮助我掌握解决此示例中的关闭问题所需的概念?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你在闭包内增加了一个
timeIncrement
。因此,在第一次超时发生之前,您根本不会增加它。以下是更改后的代码:您可能仍然遇到
wIncrement
变量的问题。此外,出于这个原因,我会使用setInterval
而不是setTimeout
。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:You still might have issues with
wIncrement
variable. Also I would usesetInterval
instead ofsetTimeout
for this reason.您不想使用
setTimeout
,而是使用setInterval
。后者将在每个时间间隔调用该函数一次,而不是仅调用一次。此外,在某些时候,您可能希望结束间隔并停止增加大小。为此,您需要对
setInterval
的结果调用clearInterval
Instead of using
setTimeout
you want to usesetInterval
. The latter will call the function once per interval instead of just once.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 ofsetInterval