How to repeat `setInterval`?

Viewed 135

How can i repeat setInterval?

So, i have a function (Duration = 19sec for 1 itteration).

First 4 seconds - label is "text 1", Next 7 seconds - label is "text 2" And next 8 seconds - label is "text 3".

And after 19s it should repeat (I have var of itterations - newCurrentElement) and i also have the hole duration of the function (timeNewCurremtElement).

timeNewCurremtElement and newCurrentElement are known, so you shouldn't worry about it.

I have tried to make a loop (for), but that did't work.

function TextChanger() {
    counter = 0;

    clearInterval(timer);

    function TextChanger_Interval(){
        timer = setInterval(function() {
            counter++;

            if (counter <= 3) {
                $('#in-hold-out').html("Inhale");

            } else if (counter <= 10) {
                $('#in-hold-out').html("Hold");

            } else if (counter <= 18) {
                $('#in-hold-out').html("Exhale");

            } else {
                counter = 0;
                clearInterval(timer);
            }

        }, 1000);
    }

    TextChanger_Interval();

}

TextChanger();

Thank you!

2 Answers

You could take an object with the time for changing the text and the text as value.

To illustrate, this example shows unchanged counting as well. if not used, delete the else part.

setInterval((i => () => {
    const parts = { 0: 'text1', 4: 'text2', 11: 'text3' };
    if (parts[i]) console.log(parts[i]);
    else console.log(i);
    i++;
    i %= 19;
})(0), 1000);

I think you are trying to do something like this

  let counter = 0;
  function TextChanger() {

    if (counter <= 3) {
      console.log(0);
    } else if (counter <= 10) {
      console.log(1);
    } else if (counter <= 18) {
      console.log(3);
    } else {
      counter = 0;
    }
    counter++
  }
  setInterval(TextChanger, 1000);
Related