Javascript setTimeout问题w / for循环 [英] Javascript setTimeout issue w/ for loop
问题描述
这是我的功能,当被调用时,相关节点变成红色,然后什么都不做。
这里是javascript:
$ p $ lt; code> function blink(node,flickers)
{
originalColour = node.style.color; $($($))
(i = 1; i <=(flickers * 2); i ++)
{
setTimeout(function(){ChangeColor(node,(((i%2)== 0)?(originalColour):('red')))},(i * 200));
ChangeColor(node,color)
{
node.style.color = color;
$ / code>
当匿名函数被调用not
被称为。 i
时,是 i
c $ c> setTimeout
您需要创建一个闭包并传递当前值 i
函数ChangeColorLater(i){
return function(){
ChangeColor(node,(((i%2)== 0)?(originalColour):('red')))
}
}
setTimeout ChangeColourLater(i),(i * 200));
This is my function, when called the related node turns red and then does nothing.
Here is the javascript:
function blink (node, flickers)
{
originalColour = node.style.color;
for (i = 1; i <= (flickers*2); i++)
{
setTimeout (function () {ChangeColor (node, (((i%2) == 0) ? (originalColour) : ('red')))}, (i*200));
}
}
function ChangeColor (node, color)
{
node.style.color = color;
}
i
is "i
when the anonymous function is called" not "i
when setTimeout
is called".
You need to create a closure and pass the current value of i
into it.
function ChangeColorLater(i) {
return function () {
ChangeColor (node, (((i%2) == 0) ? (originalColour) : ('red')))
}
}
setTimeout (ChangeColourLater(i), (i*200));
这篇关于Javascript setTimeout问题w / for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!