countup and countdown loop

Tags: ,



I want to count from 3 down to 0 then back up to 3 in a loop. This is kind of “slider” implementation. Everything runs fine until reach the clearInterval from counterry. What am I missing?

var counttx = 0, // counter
    counterrx = setInterval(timerrx, 1000), // countup - start
    counterry; // countdown after reach 3

function timerrx(){
    counttx = counttx+1;
    //console.log(counttx);
    if(counttx > 2){
        counterry = setInterval(timerry, 1000); 
        clearInterval(counterrx);
    }
}

function timerry(){
   counttx = counttx-1;
   //console.log(counttx);
   if(counttx < 2){
       setInterval(timerrx, 1000);
       clearInterval(counterry);
   }
}

Answer

Use a single loop:

let counttx = 0, countup = true;
const counter = document.getElementById('counter');

function timerr()
{
  if (countup)
  {
    ++counttx;
    
    if (counttx >= 3)
      countup = false;
  }
  else
  {
    --counttx;
    
    if (counttx <= 0)
      countup = true;
  }
  
  counter.value = counttx;
}

setInterval(timerr, 1000);
<input type="number" id="counter" value="0" />


Source: stackoverflow