我想从3倒数到0,然后循环回到3。这是一种“滑块”实现。一切正常,直到从clearInterval到达counterry为止。我想念什么?

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

最佳答案

使用一个循环:

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" />

关于javascript - 倒数循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18666687/

10-09 18:13