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;
}
The problem is that at the time each timeout executes, i is equal to flickers * 2.
Using a closure, you can capture the value of i when the timeout is set, and pass that to your ChangeColor function. At the time the callback is executed, index (below) will equal the value of i at the time that the timeout was set.
What you want is:
i
is "i
when the anonymous function is called" not "i
whensetTimeout
is called".You need to create a closure and pass the current value of
i
into it.A bit easier to read. http://jsfiddle.net/wUkfe/22/