0

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;
}

3 Answers 3

3

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));
Sign up to request clarification or add additional context in comments.

2 Comments

I am really very sorry, is this what you mean: function blink (node, flickers) { alert('start'); originalColour = node.style.color; for (i = 1; i <= (flickers*2); i++) { alert(i); setTimeout (ChangeColourLater(i, node), (i*200)); } } function ChangeColorLater(i, node) { alert("2 " + i); return function () { ChangeColor (node, (((i%2) == 0) ? (originalColour) : ('red'))) } } function ChangeColor (node, color) { node.style.color = color; }
Sorry, I have no idea what I am doing with stackoverflow - I can't get code tags to work in the comments - I will figure it out eventually
1

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:

function blink (node, flickers) {
    var originalColour = node.style.color;
    for (var i = 1; i <= (flickers*2); i++) {
        setTimeout (function (index) { // current value for i in loop becomes var index
            return function() {
                ChangeColor(node, (index % 2 == 0) ? originalColour : 'red');
            }
        }(i), i*200)
    }
}
function ChangeColor (node, color) {
    node.style.color = color;
}

Comments

0

A bit easier to read. http://jsfiddle.net/wUkfe/22/

function blink(node, flickers){

  var color = node.style.color;

  (function blinker(){

    node.style.color = (flickers % 2) ?  "red" : color;

    if (flickers--){
      setTimeout(blinker, 1000);
    }

  })();

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.