javascript - 带类倒计时器

标签 javascript jquery html timer

我的网页上有以下代码行 - example/demo .

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 处,以便第二个时钟也能工作?

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

最佳答案

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

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

关于javascript - 带类倒计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31478743/

相关文章:

javascript - 替代 TextArea 对文本进行更多控制?

javascript object.key 不工作

javascript - 犀牛的控制台输入功能?

javascript - 任何文本输入更改时运行函数

html - hover div的高度在增加

javascript - 在 Discord.js 中实例化嵌入对象时出错

javascript - 具有多种形式的 jQuery 序列化函数

javascript - 如何对包含相同 id 元素的两个 div 使用通用的 js 函数?

html - 垂直移动 <hr>

html - 为什么菜单出现在 Chrome 和 FireFox 中,而 IE 中没有?