setTimeout with loop issue with field update

2020-04-21 04:38发布

问题:

I'm trying to loop through a list on a timer (currently 1 second but I want it faster). The problem is that the current value isn't being updated visually & I can't see why.

When I loop through with Firebug it works as intended but without firebug it's not showing the text change...is it skipping the text update somehow?

I set the timer to 1 second; surely a .html() call wouldn't take longer? Thanks for any info.

My HTML is simply:

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

My JS is:

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

回答1:

You are calling nameIncrement() and passing its return value to setTimeout(), rather than passing nameIncrement.

Remove the parentheses:

run = setTimeout(nameIncrement, 1000);

jsfiddle



回答2:

It looks like you are running a recursive function without defining exit condition. this probably causes overload to the browser which decided not to run the function.

Try:

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

on debug mode, however, the browser is less defensive, so you can see your erors yourself.