简体   繁体   English

javascript中HTML表格中每一行的倒数计时器

[英]Countdown timer in javascript for each row of table in html

    var count = Number(sessionStorage.getItem('count')) || 3600;

    var counter = setInterval(timer, 1000); //1000 will  run it every 1 second
    function timer() {
    count = count - 1;
    sessionStorage.setItem('count', count)
    if (count == -1) {
        clearInterval(counter);
        return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    var time_str = hours + ":h " + minutes + ":m " + seconds + ":s";
    //document.cookie = 'time_str = hours + ":h " + minutes + ":m " +     seconds + ":s"; expires=Thu, 26 March 20:47:11 UTC; path=/'

    Array.prototype.forEach.call(document.querySelectorAll('.timer'), function (el ) { el.innerHTML = time_str; });
}

Above is my javascript code for countdown timer. 上面是我的倒计时计时器的JavaScript代码。 This works fine, but it doesn't stop after "0h:0m:0s" time. 这可以正常工作,但不会在“ 0h:0m:0s”时间之后停止。 it start counting in negative. 它开始计数为负。

Here's a modified version of your code that works for me: 这是对我有用的代码的修改版本:

var count = 5;
var counter = setInterval(hockeytimer, 1000);

function hockeytimer() {
  count = count - 1;
  sessionStorage.setItem('count', count);

  if (count == -1) {
    clearInterval(counter);
    return;
  }

  var seconds = count % 60;
  var minutes = Math.floor(count / 60);
  var hours = Math.floor(minutes / 60);
  minutes %= 60;
  hours %= 60;

  if (hours === 0 && minutes === 0  && seconds === 0 ) {
    var table = document.getElementById("hockeyt");
    while (table.rows.length > 0 ) {
      table.deleteRow();
    }
  }

  var time_str = hours + ":h " + minutes + ":m " + seconds + ":s";

  var timerCells = document.querySelectorAll('.hockeytimer');

  for (var i = 0; i < timerCells.length; i++) {
    var timerCell = timerCells[i];
    timerCell.innerHTML = time_str;
  }
}

Demo: http://jsbin.com/ceboqi/1/edit?html,js,output 演示: http : //jsbin.com/ceboqi/1/edit?html,js,output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM