JavaScript for循环和setTimeout问题 [英] Javascript for loop and setTimeout issue

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

问题描述

所以我认为下面的代码会非常简单,但已经成为头痛的问题。它应该是一个循环,将改变对象的不透明度,使它消失。



$ p $函数doSomething()
{
var i = 10; (i = 10; i> = 0; i = i-1)
{
setTimeout(setOpacity('t1',+ i +)一世);
WRITE 1



函数setOpacity(elem,hmm)
{
WRITE 2
document.getElementById elem).style.opacity =(10-hmm)/ 10;
document.getElementById(elem).style.filter ='alpha(opacity ='+(10-hmm)* 10 +')';





$ b因此问题在于for循环从10减少到0,这已被位于WRITE 1的打印语句所证实。但是,在setOpacity方法中,接收到的数字从0开始计数到10,这已经被WRITE 2的打印语句确认。

我想知道为什么会发生这种情况,以及我如何解决这个问题。我相信这与setTimeout调用在循环结束后执行方法调用有关,但是如果是这样,那么为什么这些值传递给setOpacity递增呢?


解决方案

传递给setOpacity的值正在增加,因为您正在传递不同的超时值。你的循环的结果本质上如下:

pre $ setTimeout(setOpacity('t1','10'),1000 )
setTimeout(setOpacity('t1','9'),900)
setTimeout(setOpacity('t1','8'),800)
... 。
setTimeout(setOpacity('t1','0'),0)

结果是,他们被调用的时间相反的顺序。所以最后一次调用在0ms(在函数完成之后)被执行,结果为0作为 hmm ,接着是1,2,3 ...



为了解决这个问题,你需要把 100 * i 改成 100 *(10 - i)


So I thought that the following code would be really simple but has become a big headache. It should be a loop that will change the opacity of and object so that it fades away.

function doSomething()
{
    var i = 10;
    for(i = 10; i >=0; i = i - 1)
    {
        setTimeout("setOpacity('t1',"+ i +")", 100*i);
        WRITE 1
    }
}

function setOpacity(elem, hmm)
{
    WRITE 2
    document.getElementById(elem).style.opacity = (10 - hmm)/10;
    document.getElementById(elem).style.filter = 'alpha(opacity=' + (10 - hmm)*10 + ')';
}

So the problem is that the for loop is counting down from 10 to 0 and this has been confirmed by a print statement located at WRITE 1. However in the setOpacity method the numbers being received are starting at 0 and counting to 10 and this has been confirmed by a print statement at WRITE 2.

I would like to know why this is happening and how I can fix it. I believe it has something to do with the setTimeout call executing the method call after the end of the loop, but if that is so then why are the values being passed to setOpacity incrementing?

Any help is much appreciated.

解决方案

The values being passed to setOpacity are increasing because you are passing different timeouts. The result of your loop is essentially the following:

setTimeout("setOpacity('t1', '10')", 1000)
setTimeout("setOpacity('t1', '9')", 900)
setTimeout("setOpacity('t1', '8')", 800)
....
setTimeout("setOpacity('t1', '0')", 0)

The result is that they are called in reverse order based on the timings. So the last call gets executed in 0ms (after the function finishes), resulting in 0 as hmm, followed by 1, 2, 3 ...

To fix this you need to change 100*i to 100 * (10 - i)

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

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