开发者

Javascript for loop and setTimeout issue

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 s开发者_运维问答tatement 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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜