Javascript for loop and setTimeout issue

前端 未结 1 1555
攒了一身酷
攒了一身酷 2021-01-28 17:45

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.<

相关标签:
1条回答
  • 2021-01-28 18:42

    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 讨论(0)
提交回复
热议问题