Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a simple setTimeout loop

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);

    }
like image 293
Mythical Fish Avatar asked Nov 10 '11 14:11

Mythical Fish


3 Answers

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);
like image 174
Molochdaa Avatar answered Nov 02 '22 16:11

Molochdaa


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);
like image 33
uɥƃnɐʌuop Avatar answered Nov 02 '22 15:11

uɥƃnɐʌuop


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();
})();
like image 33
Andres Separ Avatar answered Nov 02 '22 15:11

Andres Separ