setInterval似乎不能很好地在循环中工作

时间:2014-02-13 21:21:00

标签: javascript html loops

我在循环中遇到间隔问题。 这是我的代码:

for(i=0;i<=10;i++){
        (function(i){
            set = setInterval(function(){
                alert("hello, world.") // for example.
            },1000);
        })(i);
    };

我希望这发生在任何1000毫秒,但是当它开始时它会等待1000毫秒,然后像往常一样执行循环; 我可以这样处理:

var i = 0;
    set = setInterval(function(){
        alert("hello, world.");
        i++;
        if(i == 10){
            clearInterval(set);
        };
    },1000);

但我真的不想以这种方式规划我的代码。 我得用循环。 提前谢谢。


为什么这不起作用:

<div id="lbl"></div><br>
    <script>
    function fun(){
        var text = "in the name of god";
        var lbl = document.getElementById("lbl");
        var arr = new Array("a","b","c","d","e","f","g","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ",0,1,2,3,4,5,6,7,8,9);
        for(x in text){
            var spn = document.createElement("span");
            lbl.appendChild(spn);

            for(i=0;i<=arr.indexOf(text[x]);i++){
                (function(i){
                    setTimeout(function(){
                        spn.innerHTML = arr[i];
                    },i*200);
                })(i);
            };              
        };
    };
    fun();
    </script>

1 个答案:

答案 0 :(得分:0)

你需要反转它 - 让定时器驱动循环,而不是循环驱动定时器。 根据您的示例:

<label id="lbl"></label><br>
<script>

function ok(a){
    var arr = new Array("a","b","c","d","e","f","g","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",0,1,2,3,4,5,6,7,8,9);
    var lbl = document.getElementById("lbl");
    var i = 0, iMax = arr.indexOf(a);

    function next()
    {   
        lbl.innerHTML = arr[i];
        if (++i <= iMax) {
            setTimeout(next,i * 200);
        }                
    }
    setTimeout(next,0);
}
ok("z");
</script>