带有循环问题的setTimeout和字段更新

时间:2014-02-07 22:54:22

标签: loops field settimeout

我正在尝试循环计时器上的列表(目前为1秒,但我希望它更快)。问题是当前值没有在视觉上和我不明白为什么。

当我使用 Firebug 进行循环时,正常工作但没有firebug它没有显示文本更改...是否以某种方式跳过文本更新?

我将计时器设置为1秒;肯定会.html()调用不会花费更长时间?感谢您的任何信息。

我的HTML很简单:

<div id="winner2"><h1></h1></div>
<div id="button"">
<img id="start" src="start.png" />
<img id="stop" src="stop.png" />
</div>

我的JS是:

var people = ["a", "b", "c"];
        var counter = 1;
        var run;
        $(document).ready(function(){ 
        $("#winner2 h1").html("a");
        $("#stop").hide();

        $( "#start" ).click(function() {
            $("#start").hide();
            $("#stop").show();
            run = setTimeout (nameIncrement(),1000);
        });

        $( "#stop" ).click(function() {
            $("#stop").hide();
            $("#start").show();
            clearTimeout(run);
        });

        function nameIncrement() {
            if(counter == people.length) {
                counter=0;
            }       
            $("#winner2 h1").html(people[counter]);
            counter++;
            run = setTimeout (nameIncrement(),1000);
        }       
        }); 

2 个答案:

答案 0 :(得分:1)

您正在调用nameIncrement()并将其返回值传递给setTimeout(),而不是传递nameIncrement

删除括号:

run = setTimeout(nameIncrement, 1000);

jsfiddle

答案 1 :(得分:0)

看起来您正在运行递归函数而不定义退出条件。这可能导致浏览器过载,决定不运行该功能。

尝试:

function nameIncrement() {
            if(counter == people.length) {
                counter=0;
                return;
            }       
            $("#winner2 h1").html(people[counter]);
            counter++;
            run = setTimeout (nameIncrement(),1000);
        }       
        });

在调试模式下,浏览器的防御性较差,因此您可以自己查看自己的错误。

相关问题