JavaScript Closures和setTimeout [英] JavaScript Closures and setTimeout

查看:98
本文介绍了JavaScript Closures和setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

闭包是我在JS中仍然没有完全掌握的东西。我认为这是一个关闭问题。我试图创建一个进度条。每x秒我想增加一个DIV的宽度。这是应该这样做的部分:

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);
}

我想要发生的是每x秒,增加bar的大小。如果当然,这不是发生了什么。

What I want to happen is every x seconds, increase the size of the bar. If course, that's not what's happening.

我很肯定(希望),这是一个关闭问题,但与setTimout混合的语法完全flummoxes我。任何人都可以帮助我抓住解决这个例子中的封闭问题所需的概念?

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?

推荐答案

事情是你在闭包中增加一个 timeIncrement 。因此,有效地,您不会增加在所有,直到第一个超时发生。以下是已更改的代码:

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);
}

您可能仍有 wIncrement 变量。因为这个原因,我会使用 setInterval 而不是 setTimeout

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

这篇关于JavaScript Closures和setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆