当我的计时器达到零时调用一个函数

时间:2016-06-14 03:26:35

标签: javascript

我有一个计时器功能,如下所示(我刚刚抓住了一个jsfiddle):

function countdown( elementName, minutes, seconds )
{
    var element, endTime, hours, mins, msLeft, time;

    function returnDate(){
    return Number(new Date);
    }

    function twoDigits( n )
    {
        return (n <= 9 ? "0" + n : n);
    }

    function updateTimer()
    {
        msLeft = endTime - (returnDate());
        if ( msLeft < 1000 ) {
            element.innerHTML = "0:00";
        } else {
            time = new Date( msLeft );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }

    element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
}

我调用该函数并将其设置为倒计时2分钟,如下所示:

$(".btn-start").click(function(){
 countdown("countdown-2-minutes",2,0);

});

我有另一个标识为countdown-8-minutes的元素,当countdown-2-minutes上的计时器达到0时我想立即启动。我应该怎么做?我想一个好的方法是监视第一个元素上的html何时读取“0:00”,但我不知道如何实现它。

3 个答案:

答案 0 :(得分:1)

这是我的建议;首先更改您的countdown()函数以接受回调参数:

function countdown( elementName, minutes, seconds, callback )
{
    var element, endTime, hours, mins, msLeft, time;

    function returnDate(){
    return Number(new Date);
    }

    function twoDigits( n )
    {
        return (n <= 9 ? "0" + n : n);
    }

    function updateTimer()
    {
        msLeft = endTime - (returnDate());
        if ( msLeft < 1000 ) {
            element.innerHTML = "0:00";
            if (typeof callback === 'function') {
                callback.call()
            }
        } else {
            time = new Date( msLeft );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }

    element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
}

然后通过初始调用传递回调:

$(".btn-start").click(function(){
    countdown("countdown-2-minutes",2,0, function(){countdown("countdown-8-minutes",8,0);});
});

答案 1 :(得分:0)

您无需观察元素的内容即可知道何时启动下一个计时器。事实上,您已经对检查if ( msLeft < 1000 ) {行中发生的事情做出了反应,您可以在其中启动下一个计时器。

一旦你的当前计时器达到零,你就可以在if语句中启动下一个计时器。

或者,您可以使用以下内容将计时器逻辑与元素逻辑分开:

// CountdownTimer object. Give it a length (ms) to count to, a period (ms)
// to loop updates to the callback, and a callback (function(done:bool)) that
// handles update ticks where done=false and the final tick where done=true.

function CountdownTimer(length, period, callback) {
  this.length = length;
  this.period = period;
  this.callback = callback;
  
  // Assert the callback to be a function to avoid messy error handling, and
  // show we noticed in the console.

  if (typeof this.callback !== 'function') {
    console.warn('Callback was not a function.');
    this.callback = function(){};
  }
  
  // Some publically visible variables for time keeping.

  this.startTime = 0;
  this.elapsed = 0;
  this.remaining = length;
  
  // The _loop scope's 'this' is itself. Give it a handle on the CountdownTimer's
  // 'this' so we can reference the variables inside the loop.
  var scope = this;
  
  // Main loop of the countdown timer.

  this._loop = function() {

    // Get the number of milliseconds since the countdown started.
    scope.elapsed = Date.now() - scope.startTime;

    if (scope.elapsed < scope.length) {

      // Keep looping if the countdown is not yet finished.
      scope.remaining = scope.length - scope.elapsed;
      scope.callback(false);

    } else {

      // Finished looping when the countdown hits or passes the target.
      scope.elapsed = scope.length;
      scope.remaining = 0;
      scope.callback(true);
      // Stop the interval timer from looping again.
      clearInterval(scope._t);

    }
  };
}

// This function starts up the CountdownTimer
CountdownTimer.prototype.start = function() {
  this.startTime = Date.now();
  this._t = setInterval(this._loop, this.period);
}

// Our test elements.
var progress2 = document.getElementById('prog-2m');
var progress8 = document.getElementById('prog-8m');
var clockElement = document.getElementById('clock');
var startButton = document.getElementById('start');

// The 2-minute timer.

var m2 = new CountdownTimer(2 * 60 * 1000, 33, function(done) {

  // Calculate the time to display.
  var mins = Math.floor(m2.remaining / 60 / 1000);
  var secs = Math.floor(m2.remaining / 1000) % 60;
  if (secs < 10) secs = '0' + secs;
  clockElement.textContent = mins + ':' + secs;

  if (done) {

    // If we're done, set the timer to show zero and start the next timer.
    clockElement.textContent = '0:00';
    m8.start();

  }

  // Progress bar display update.
  progress2.style.width = (40 * (m2.elapsed / m2.length)) + 'px';
  progress8.style.width = (160 * (m8.elapsed / m8.length)) + 'px';

});

// The 8-minute timer.

var m8 = new CountdownTimer(8 * 60 * 1000, 33, function(done) {

  // Calculate the time to display.
  var mins = Math.floor(m8.remaining / 60 / 1000);
  var secs = Math.floor(m8.remaining / 1000) % 60;
  if (secs < 10) secs = '0' + secs;
  clockElement.textContent = mins + ':' + secs;

  if (done) {

    // Once done, set the timer to zero and display "Done".
    clockElement.textContent = '0:00 Done';
  }

  // Progress bar display update.
  progress2.style.width = (40 * (m2.elapsed / m2.length)) + 'px';
  progress8.style.width = (160 * (m8.elapsed / m8.length)) + 'px';
});

// Start the 2-minute timer when the button is clicked.
startButton.addEventListener('click', function() {
  m2.start();
});
#progress {
  width: 200px;
  height: 20px;
  border: 2px solid #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  border-radius: 2px;
  position: relative;
  margin: 8px 0;
}
#prog-2m {
  width: 40px;
  height: 20px;
  background-color: #3c9;
  position: absolute;
  left: 0;
  top: 0;
}
#prog-8m {
  width: 160px;
  height: 20px;
  background-color: #c33;
  position: absolute;
  left: 40px;
  top: 0;
}
<div id="progress">
  <div id="prog-2m"></div>
  <div id="prog-8m"></div>
</div>
<div id="clock">0:00</div>
<button id="start">Begin</button>

答案 2 :(得分:0)

当您检测到计时器完成时,只需使用适当的参数调用countdown()。试试这个:

if ( msLeft < 1000 ) {
    element.innerHTML = "0:00";
    countdown("countdown-8-minutes",8,0);
}