倒计时器与类

时间:2015-07-17 14:57:07

标签: javascript jquery html timer

我的网页上有以下代码行 - here

HTML:

<p class="countdown-timer">10:00</p>

<p class="countdown-timer">10:00</p>

JavaScript的:

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;

    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

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

        display.textContent = minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };

    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

$(document).ready(function(){
    // set the time (60 seconds times the amount of minutes)
    var tenMinutes = 60 * 10,
        display = document.querySelector('.countdown-timer');
    startTimer(tenMinutes, display);
}); 

由于我对JavaScript / jQuery相对较新,我怎样才能使定时器停在0并且第二个时钟也能正常工作?

我尝试用document.querySelector('.countdown-timer');

替换$('.countdown-timer');

4 个答案:

答案 0 :(得分:1)

我之前创建了一个类,用于我的一个项目。它允许您拥有多个具有不同设置的计数器。它还可以配置为使用可用功能通过按钮暂停或重置。看看它是如何完成的,它可能会给你一些提示:

/******************
 * STOPWATCH CLASS
 *****************/

function Stopwatch(config) {
  // If no config is passed, create an empty set
  config = config || {};
  // Set the options (passed or default)
  this.element = config.element || {};
  this.previousTime = config.previousTime || new Date().getTime();
  this.paused = config.paused && true;
  this.elapsed = config.elapsed || 0;
  this.countingUp = config.countingUp && true;
  this.timeLimit = config.timeLimit || (this.countingUp ? 60 * 10 : 0);
  this.updateRate = config.updateRate || 100;
  this.onTimeUp = config.onTimeUp || function() {
    this.stop();
  };
  this.onTimeUpdate = config.onTimeUpdate || function() {
    console.log(this.elapsed)
  };
  if (!this.paused) {
    this.start();
  }
}


Stopwatch.prototype.start = function() {
  // Unlock the timer
  this.paused = false;
  // Update the current time
  this.previousTime = new Date().getTime();
  // Launch the counter
  this.keepCounting();
};

Stopwatch.prototype.keepCounting = function() {
  // Lock the timer if paused
  if (this.paused) {
    return true;
  }
  // Get the current time
  var now = new Date().getTime();
  // Calculate the time difference from last check and add/substract it to 'elapsed'
  var diff = (now - this.previousTime);
  if (!this.countingUp) {
    diff = -diff;
  }
  this.elapsed = this.elapsed + diff;
  // Update the time
  this.previousTime = now;
  // Execute the callback for the update
  this.onTimeUpdate();
  // If we hit the time limit, stop and execute the callback for time up
  if ((this.elapsed >= this.timeLimit && this.countingUp) || (this.elapsed <= this.timeLimit && !this.countingUp)) {
    this.stop();
    this.onTimeUp();
    return true;
  }
  // Execute that again in 'updateRate' milliseconds
  var that = this;
  setTimeout(function() {
    that.keepCounting();
  }, this.updateRate);
};

Stopwatch.prototype.stop = function() {
  // Change the status
  this.paused = true;
};



/******************
 * MAIN SCRIPT
 *****************/

$(document).ready(function() {
  /*
   * First example, producing 2 identical counters (countdowns)
   */
  $('.countdown-timer').each(function() {
    var stopwatch = new Stopwatch({
      'element': $(this),               // DOM element
      'paused': false,                  // Status
      'elapsed': 1000 * 60 * 10,        // Current time in milliseconds
      'countingUp': false,              // Counting up or down
      'timeLimit': 0,                   // Time limit in milliseconds
      'updateRate': 100,                // Update rate, in milliseconds
      'onTimeUp': function() {          // onTimeUp callback
        this.stop();
        $(this.element).html('Go home, it\'s closing time.');
      },
      'onTimeUpdate': function() {      // onTimeUpdate callback
        var t = this.elapsed,
            h = ('0' + Math.floor(t / 3600000)).slice(-2),
            m = ('0' + Math.floor(t % 3600000 / 60000)).slice(-2),
            s = ('0' + Math.floor(t % 60000 / 1000)).slice(-2);
        var formattedTime = h + ':' + m + ':' + s;
        $(this.element).html(formattedTime);
      }
    });
  });
  /*
   * Second example, producing 1 counter (counting up to 6 seconds)
   */
  var stopwatch = new Stopwatch({
    'element': $('.countdown-timer-up'),// DOM element
    'paused': false,                    // Status
    'elapsed': 0,                       // Current time in milliseconds
    'countingUp': true,                 // Counting up or down
    'timeLimit': 1000 * 6,              // Time limit in milliseconds
    'updateRate': 100,                  // Update rate, in milliseconds
    'onTimeUp': function() {            // onTimeUp callback
      this.stop();
      $(this.element).html('Countdown finished!');
    },
    'onTimeUpdate': function() {        // onTimeUpdate callback
      var t = this.elapsed,
          h = ('0' + Math.floor(t / 3600000)).slice(-2),
          m = ('0' + Math.floor(t % 3600000 / 60000)).slice(-2),
          s = ('0' + Math.floor(t % 60000 / 1000)).slice(-2);
      var formattedTime = h + ':' + m + ':' + s;
      $(this.element).html(formattedTime);
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
These 2 timers should count down from 10 minutes to 0 seconds:
<p class="countdown-timer">00:10:00</p>
<p class="countdown-timer">00:10:00</p>
But this one will count from 0 to 6 seconds:
<p class="countdown-timer-up">00:00:00</p>

答案 1 :(得分:0)

我认为你的问题是你将一个数组传递给startTimer函数,所以它只是为第一个项目做的。

如果您准备好文档,以便为.countdown-timer的每个实例启动一个计时器,它应该可以工作:

// set the time (60 seconds times the amount of minutes)
var tenMinutes = 60 * 10;

$('.countdown-timer').each(function () {
  startTimer(tenMinutes, this);
});

Example

答案 2 :(得分:0)

document.querySelector('。class')只会找到第一个带.class的元素。如果您已经在使用jQuery,我建议您这样做:

var display = $('.countdown-timer');
for (var i = 0; i < display.length; i++) {
    startTimer(tenMinutes, display[i]);
}

这种方式适用于任意数量的倒数计时器。

答案 3 :(得分:0)

我们走了,jsfiddle

刚刚将querySelector更改为getElementsByClassName以获取具有相同类的所有p元素。您可以使用它的索引在不同元素上启动计时器。 不需要队列:D

$(document).ready(function(){
   // set the time (60 seconds times the amount of minutes)
    var tenMinutes = 60 * 10,
        display = document.getElementsByClassName('countdown-timer');

    startTimer(tenMinutes, display[0]);
    startTimer(tenMinutes, display[1]);
});