Javascript将countDown计时器更改为countUp时间

时间:2019-02-26 01:55:18

标签: javascript

我有一个带有内置延迟功能的倒数计时器javascript。我需要将其更改为具有相同延迟功能的递增计时器。我和我一起知道如何在此处发布问题,因为这似乎不容易接受。让我们看看这是否可行...

<script type="text/javascript">
  function pad(num, size) {
    var s = num+"";
    while (s.length < size) 
      s = "0" + s;
    return s;
  }

  function initCountdown(){
    setTimeout(function() {
      current_wait++;

      if(current_wait <= waits.length) {
        var countdowns = document.getElementsByClassName('countdown');
        for(var i = 0; i < countdowns.length; i++) {
          var number = parseInt(countdowns[i].innerHTML);
          number--;

          countdowns[i].innerHTML = pad(number, 2);
        }
        initCountdown();
      }
    }, waits[current_wait] * 1000);
  }

  var initial_number = 7;
  var waits          = [4, 24, 55]; //ADD HERE AS MANY SECONDS AS YOU DESIRE.
  var current_wait   = 0;

  var countdowns = document.getElementsByClassName('countdown');

  for(var i = 0; i < countdowns.length; i++){               
    countdowns[i].innerHTML = pad(initial_number, 2);
  }

  initCountdown();
</script>

2 个答案:

答案 0 :(得分:0)

如果您想将代码更改为向上计数,则只需将initial_number设置为起始值(例如1),并将代码number--设置为number++ < / p>

The simplest possible JavaScript countdown timer?

中可以找到一个简单的计数计时器的好例子。

function pad(num, size) {
  var s = num + "";
  while (s.length < size) s = "0" + s;
  return s;
}

function initCountdown() {
  setTimeout(function() {
    current_wait++;

    if (current_wait <= waits.length) {
      var countdowns = document.getElementsByClassName('countdown');

      for (var i = 0; i < countdowns.length; i++) {
        var number = parseInt(countdowns[i].innerHTML);
        number++;

        countdowns[i].innerHTML = pad(number, 2);
      }

      initCountdown();
    }
  }, waits[current_wait] * 1000);
}

var initial_number = 1;
var waits = [4, 24, 55]; //ADD HERE AS MANY SECONDS AS YOU DESIRE.
var current_wait = 0;

var countdowns = document.getElementsByClassName('countdown');

for (var i = 0; i < countdowns.length; i++) {
  countdowns[i].innerHTML = pad(initial_number, 2);
}

initCountdown();
<div class='countdown'></div>

答案 1 :(得分:0)

function pad(num, size) {
  var s = num + "";
  while (s.length < size) {
    s = "0" + s;
  }

  return s;
}

function createCountdown(initialTime, finalTime) {
  var currentTime = initialTime;

  return setInterval(function() {
    var countdowns = document.getElementById("countdown");
    if (currentTime >= finalTime) {
        countdowns.innerHTML = pad(currentTime--, 2);
    }
  }, 1000);
}

var countdown = createCountdown(30, 0);

// Execute this to stop the countdown at anytime
// clearInterval(countdown);
<div id="countdown"></div>