setTimeout with loop issue with field update

前端 未结 2 1782
死守一世寂寞
死守一世寂寞 2021-01-24 03:31

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 w

相关标签:
2条回答
  • 2021-01-24 04:10

    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.

    0 讨论(0)
  • 2021-01-24 04:16

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

    Remove the parentheses:

    run = setTimeout(nameIncrement, 1000);
    

    jsfiddle

    0 讨论(0)
提交回复
热议问题