Javascript counter works only once

谁都会走 提交于 2019-12-26 03:49:23

问题


I have a jsfiddle here - http://jsfiddle.net/5z2vu47a/

It's a simple timer that should change text that taken from and array

The timer only works once.

Why does the timer not continue to work.

var name_arr = ['learn', 'product', 'buying', 'selling', 'marketing', 'managing', ];
var counter = 0;

function names(){
    alert(counter);
    $('.text p').text(name_arr[counter]);
    counter++;
    alert(counter);
}

setTimeout(names, 1000);

回答1:


You need to use setInterval

setInterval(names, 1000);

In the names function, also check that the counter value should not exceed the name_arr.length.

function names(){
    alert(counter);
    $('.text p').text(name_arr[counter]);
    if(counter<(name_arr.length-1))
     counter++;
    else
     counter=0;
    alert(counter);
}



回答2:


setTimeout runs only once, after a specified delay.
As stated in MDN WindowTimers.setTimeout()

Calls a function or executes a code snippet after a specified delay.

setInterval runs in intervals, spaced by a specified delay. As stated in MDN WindowTimers.setInterval()

Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.

So, setInterval will run forever, unless you break it with a clearInterval.

function doStuff() {
    // Doing ome nice and fancy stuff here...
}

var interval = setInterval(doStuff, 1000);

// this will stop the interval loop
clearInterval(interval);



回答3:


You used setTimeout, which waits 1 second and then does your function.

You want setInterval



来源:https://stackoverflow.com/questions/30464492/javascript-counter-works-only-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!