How to create a simple setTimeout loop
If you want an infinite loop, you should be using setInterval()
. This will run an infinite loop, each time running the next variation:
var i=0;
setInterval(function() {
switch(i++%3) {
case 0: alert("variation 1");
break;
case 1: alert("variation 2");
break;
case 2: alert("variation 3");
break;
}
}, 2000);
If you later decide you need to stop the repeating code, store the return value when you set the interval and clear it:
var intervalId = setInterval(function() {
...
}, 1000);
clearInterval(intervalId);
try that :
var count = 1;
function transition() {
if(count == 1) {
$('#ele').html('variation 2');
count = 2;
} else if(count == 2) {
$('#ele').html('variation 3');
count = 3;
} else if(count == 3) {
$('#ele').html('variation 1');
count = 1;
}
}
setInterval(transition, 2000);
This is the best solution:
The clearTimeout() method clears a timer set with the setTimeout() method.
(function(){
var timer, count=1;
function transition(){
clearTimeout(timer);
switch(count){
case 1: count = 2; break;
case 2: count = 3; break;
case 3: count = 1; break;
}
$('#ele').html('variation ' + count);
timer = setTimeout(transition, 2000);
}
transition();
})();