繁体   English   中英

循环延迟

[英]Delay in for-loop

我想遍历一个数组并在每次迭代时分配一个颜色。 设置颜色后,我想延迟到下一次迭代,然后再次更改颜色。

这是我目前的代码,但我无法在just1数组的for循环的每次迭代之间创建延迟。

var colors = new Array("Good","Warning","Bad");
var crntcolor= 0;
just1=[[2.8077203491999057, -1.0756484331027858], [5.4610502752805568, -1.1574541704299315], [2.414925300315495, -1.506728995633369], [11.3143165555403673, -1.4461945021353346]];
function ChangeText()
{
    document.getElementById('changeText').innerHTML = colors[crntcolor];          
    for(i=0; i<just1.length; i++)
    {
    if(just1[i][0] >= -5 && just1[i][0] <= 5)
    {        
        crntcolor =0;
    }
    else if (just1[i][0] > 5 && just1[i][0] <= 10)
    {
        crntcolor = 1;
    }
    else if (just1[i][0] > 10)
    {
        crntcolor = 2;
    }
    setTimeout("ChangeText();",1000);
}
}

ChangeText();

我想你想要做的是循环数组,每个元素之间有一个延迟。 您需要摆脱for循环并一次只更改一个元素的文本:

var colors = new Array("Good","Warning","Bad");
var crntcolor= 0;
var just1 = [[2.8077203491999057, -1.0756484331027858], [5.4610502752805568, -1.1574541704299315], [2.414925300315495, -1.506728995633369], [11.3143165555403673, -1.4461945021353346]];
function ChangeText(index)
{
    document.getElementById('changeText').innerHTML = colors[crntcolor];          

    if(just1[index][0] >= -5 && just1[index][0] <= 5)
    {        
        crntcolor =0;
    }
    else if (just1[index][0] > 5 && just1[index][0] <= 10)
    {
        crntcolor = 1;
    }
    else if (just1[index][0] > 10)
    {
        crntcolor = 2;
    }
    if(index < just1.length)
    {
        setTimeout(function() { ChangeText(index+1); },1000);
    }

}

ChangeText(0);

我不确定你the delay between the text specific to the array data present in just1是什么意思。 据我所知,你已经指定了一个固定的延迟(1000)。 你的意思是你想根据数组中的值来获得不同的延迟吗? 如果是这样,您可以更改循环中的值:

setTimeout(function() { ChangeText(index+1); },1000 * just1[index][0]);

这会将延迟设置为

循环遍历数组时,分别为2.8,5.45,2.41和11.31

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM