Javascript setTimeout问题w / for循环 [英] Javascript setTimeout issue w/ for loop

查看:127
本文介绍了Javascript setTimeout问题w / for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的功能,当被调用时,相关节点变成红色,然后什么都不做。

这里是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆