Javascript setTimeout issue w/ for loop

前端 未结 3 751
天命终不由人
天命终不由人 2021-01-28 02:32

This is my function, when called the related node turns red and then does nothing.
Here is the javascript:

function blink (node, flickers)
{
    originalColo         


        
3条回答
  •  忘了有多久
    2021-01-28 03:06

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

提交回复
热议问题