jquery在彼此之后启动多个计时器

时间:2016-09-12 07:22:11

标签: javascript jquery timer countdown

我有这段代码

var duration = 60 * $(".duration").val(),
display = $(".timer");
startTimer(duration, display);

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.html(minutes + ":" + seconds);

        if (--timer < 0) {
            display.html("DONE!");
        }
    }, 1000);
}

我有+按钮让用户添加多个这样的计时器

<input type="text" class="duration" /> //Desired duration for first timer
<div class="timer"></div>

<input type="text" class="duration" /> //Desired duration for second timer
<div class="timer"></div>

<input type="text" class="duration" /> //Desired duration for third timer
<div class="timer"></div>

之后我希望用户点击一个按钮来启动计时器,但是在第一个计时器完成后,第二个计时器启动等等一次

谢谢

1 个答案:

答案 0 :(得分:1)

这是我想到的第一种没有对现有startTimer()函数进行大量更改的方法 - 基本上我只是添加了一个回调参数,然后是另一个函数来启动下一个计时器。 (这段代码可以整理一下,但它应该给你一些想法......)

&#13;
&#13;
$("button").click(function() {

  var durations = $(".duration");
  var current = -1;

  durations.prop("disabled", true);
  $(this).prop("disabled", true);

  function startNext() {
    if (++current < durations.length)
      startTimer(durations.eq(current).val() * 60,
                 durations.eq(current).next(),
                 startNext);
    else {
      durations.prop("disabled", false);
      $("button").prop("disabled", false);
    }
  }

  startNext();

  function startTimer(duration, display, callback) {
    var timer = duration,
      minutes, seconds;
    var intId = setInterval(function() {
      minutes = parseInt(timer / 60, 10)
      seconds = parseInt(timer % 60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      display.html(minutes + ":" + seconds);

      if (--timer < 0) {
        display.html("DONE!");
        clearInterval(intId);
        callback();
      }
    }, 1000);
  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
First:
<input type="text" class="duration" value="0.05" />
<div class="timer"></div>

Second:
<input type="text" class="duration" value="0.05" />
<div class="timer"></div>

Third:
<input type="text" class="duration" value="0.1" />
<div class="timer"></div>

<button>Start</button>
&#13;
&#13;
&#13;