Javascript Counter Works Only Once
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 conti
Solution 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
.
functionnames(){
alert(counter);
$('.text p').text(name_arr[counter]);
if(counter<(name_arr.length-1))
counter++;
else
counter=0;
alert(counter);
}
Solution 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
.
functiondoStuff() {
// Doing ome nice and fancy stuff here...
}
var interval = setInterval(doStuff, 1000);
// this will stop the interval loopclearInterval(interval);
Solution 3:
You used setTimeout
, which waits 1 second and then does your function.
You want setInterval
Post a Comment for "Javascript Counter Works Only Once"