I simply need to create an infinite loop through 3 variations of an element. This is what I have so far:
var count = 1;
setTimeout(transition, 2000);
function transition() {
if(count == 1) {
$('#ele').html('variation 2');
var count = 2;
} else if(count == 2) {
$('#ele').html('variation 3');
var count = 3;
} else if(count == 3) {
$('#ele').html('variation 1');
var count = 1;
}
setTimeout(transition, 2000);
}
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);
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);
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();
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With