Mythical Fish
Mythical Fish

Reputation: 293

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

    }

Upvotes: 15

Views: 59265

Answers (7)

Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18803

$(document).ready(function () {
    $("[data-count]").each(function () {
        counter($(this), .5)
    });

    function counter(el, speed) {
        let number = el.data("count"),
            count_type = el.data("count-type"),
            i = count_type === "up" ? 0 : number;

        let inter_val = setInterval(function () {
            el.text(i);
            i = count_type === "up" ? i + 1 : i - 1;
            if ((count_type === "up" && i > number) || (count_type === "down" && i < 0))
                clearInterval(inter_val);
        }, speed);
    }
});
span {
    background-color: #eeeeee;
    color: #333;
    padding: 15px 25px;
    margin: 10px;
    display: inline-block;
    width: 100px;
    text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>COUNT UP EXAMPLE</p>
<span data-count="1650" data-count-type="up"></span>
<span data-count="2500" data-count-type="up"></span>
<span data-count="985" data-count-type="up"></span>
<br>
<p>COUNT DOWN EXAMPLE</p>
<span data-count="1650" data-count-type="down"></span>
<span data-count="2500" data-count-type="down"></span>
<span data-count="985" data-count-type="down"></span>

Upvotes: 0

Gholamreza Fathpour
Gholamreza Fathpour

Reputation: 195

if you still want to use setTimeout and clearTimeout to create a loop you should use something like this structure for your loop

var count = 1;
var timer = setTimeout( function(){
    transaction();
} , 2000);

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;
    }
    //if(condition for continue) 
    setTimeout(transition, 2000);
    //else if you want to stop the loop
    //clearTimeout(timer, 2000);
}

Upvotes: 0

Mohamed Abulnasr
Mohamed Abulnasr

Reputation: 597

My best way in real life jobs is to "Forget Basic Loops" in this case and use this combination of "setInterval" includes "setTimeOut"s:

    function iAsk(lvl){
        var i=0;
        var intr =setInterval(function(){ // start the loop 
            i++; // increment it
            if(i>lvl){ // check if the end round reached.
                clearInterval(intr);
                return;
            }
            setTimeout(function(){
                $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
            },50);
            setTimeout(function(){
                 // do another bla bla bla after 100 millisecond.
                seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                $("#d"+seq[i-1]).prop("src",pGif);
                var d =document.getElementById('aud');
                d.play();                   
            },100);
            setTimeout(function(){
                // keep adding bla bla bla till you done :)
                $("#d"+seq[i-1]).prop("src",pPng);
            },900);
        },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
    }

PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.

PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..

Upvotes: 0

Andres Separ
Andres Separ

Reputation: 3394

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

Upvotes: 3

Jim H.
Jim H.

Reputation: 5579

You have var in front of your count variable inside the transition function. Remove them and the outer count variable will hold its value.

Upvotes: 0

uɥƃnɐʌuop
uɥƃnɐʌuop

Reputation: 15103

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

Upvotes: 14

Molochdaa
Molochdaa

Reputation: 2218

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

Upvotes: 20

Related Questions