javascript - 每日倒计时器 - 在 21 :57 显示消息

标签 javascript time timer countdown countdowntimer

我正在努力弄清楚 Date() 是如何工作的,我在网上找到了这个,并希望进行一个在 UTC 时间 21:57 停止的倒计时。目前,它在 21:00 显示该消息,并一直显示到 22:00。

我尝试添加 if(currenthours != 21 && currentminutes >= 57){ 但总是破坏它并收到消息。我希望它在 22:00 之前 3 分钟停止并显示消息。到了 22:00 后,第二天 21:57 重新开始倒计时。

任何帮助将不胜感激!

var date;
var display = document.getElementById('time'); 

setInterval(function(){ 
  date = new Date( );
  var currenthours = date.getUTCHours();
  // alert(currenthours);
  var currentminutes = date.getUTCMinutes();
  // alert(currentminutes);
  var hours;
  var minutes;
  var secondes;
  
  if (currenthours != 21) {

    if (currenthours < 21) {
      hours = 20 - currenthours;
    } else {
      hours = 21 + (24 - currenthours);
    }
    minutes = 60 - date.getUTCMinutes();
    secondes = 60 - date.getUTCSeconds();
    display.innerHTML = ('00' + hours).slice(-2) + ' HOURS ' + '<p>' + 
                        ('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
                        ('00' + secondes).slice(-2) + ' SECONDS';
  } else {
    display.innerHTML =  "IT'S 21:57";
  }
},1000);
<div id='time'></div>

做了一个 fiddle https://jsfiddle.net/5qrs0tcp/1/

这就是我最终得到的结果:

    /*
    |================================|
    |         COUNTDOWN TIMER        |
    |================================|
    */

    // Return the UTC time component of a date in h:mm:ss.sss format
    if (!Date.prototype.toISOTime) {
      Date.prototype.toISOTime = function() {
        return this.getUTCHours() + ':' + 
               ('0' + this.getUTCMinutes()).slice(-2) + ':' +
               ('0' + this.getUTCSeconds()).slice(-2);
      }
    }

    // Return the difference in time between two dates
    // in h:mm:ss.sss format
    if (!Date.prototype.timeDiff) {
      Date.prototype.timeDiff = function(date2) {
        var diff = Math.abs(this - date2);
        return timeobj = {
              hours   : (diff/3.6e6|0),                                    // hours
              minutes : ('0' + ((diff%3.6e6)/6e4|0)).slice(-2),            // minutes
              seconds : ('0' + ((diff%6e4)/1e3|0)).slice(-2)               // seconds
          }
      }
    }

    function countDown() {
      var now = new Date();
      var limitHr  = 19;
      var limitMin = 55;
      var limitDate = new Date(+now);
      // Set limitDate to next limit time
      limitDate.setUTCHours(limitHr, limitMin, 0, 0);

      // var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
      var msg = [];
      var diff;

      // If outside limitHr:limitMin to (limitHr + 1):00
      if (now.getUTCHours() == limitHr && now.getUTCMinutes() >= limitMin) {
         msg.push('Countdown stopped'); 

       setTimeout(function(){
        msg = ['Wait for it'];

        var jsonCounter = {
            stats          : msg
        }

        jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
       },5000);


         var jsonCounter = {
             stats          : msg
         }

         jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});

      } else {

        if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);

        var jsonCounter = {
            hours      : now.timeDiff(limitDate).hours,
            minutes    : now.timeDiff(limitDate).minutes,
            seconds    : now.timeDiff(limitDate).seconds,
            validating : msg
        }
        jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});

      }
    }

     setInterval(countDown, 1000);

    var daily_status;
    setTimeout( function(){
    setInterval( function() {
    jsonfile.readFile(DailyGamePath, (err, obj) => {
        daily_status={
          hours: obj.hours,
          minutes: obj.minutes,
          seconds: obj.seconds,
          stats: obj.stats,
          validating: obj.validating
        };
        return daily_status;
      });
    }, 1000);
    }, 3000);

    setTimeout( function(){
    io.sockets.on('connection', (socket) => {
       setInterval( function() {
          // var GameStatus=DailyGameStatus();
          socket.broadcast.emit('stream', {hours:daily_status.hours, minutes:daily_status.minutes, seconds:daily_status.seconds, stats:daily_status.stats, validating:daily_status.validating});
       }, 1000);
    });
    }, 3000);

最佳答案

日期对象非常简单,它们只是一个时间值和一些方便的方法。

我认为你的逻辑只需:

if (currenthours != 21 && currentminutes < 57) {
  // set the out of hours message
} else {
  // time is from 21:57 to 21:59 inclusive
}

倒计时不太有效,因为您数到 00,而不是 57,但除此之外似乎没有问题。

var date;
var display = document.getElementById('time'); 

setInterval(function(){
  date = new Date( );
  var currenthours = date.getUTCHours();
  var currentminutes = date.getUTCMinutes();
  var hours;
  var minutes;
  var secondes;
  var limitHr = 5;    // Change these to required values 
  var limitMin = 02;  // Using 5:12 for convenience
  var message  = 'Currently: ' + date.toISOString() + '<p>';

  // Create new message if outside limitHr:limitMin to limitHr:59 inclusive
  if (currenthours != limitHr || currentminutes < limitMin) {

    if (currenthours <= limitHr) {
      hours = limitHr - currenthours;
    } else {
      hours = limitHr + (24 - currenthours);
    }
    
    minutes  = limitMin - date.getUTCMinutes();
    minutes += minutes < 0? 60 : 0; 
    secondes = 60 - date.getUTCSeconds();
    message += ('00' + hours).slice(-2) + ' HOURS ' + '<p>' + 
               ('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
               ('00' + secondes).slice(-2) + ' SECONDS';
  } else {
    message += 'It\'s on or after ' + limitHr + ':' + 
                ('0'+limitMin).slice(-2) + ' GMT';
  }
  // Display the message
  display.innerHTML =  message;
},1000);
<div id="time"></div>

是的,计时器有问题,但这不是问题的一部分。对于计数器来说,只处理时差会更简单,因此我在 Date.prototype 中添加了一些用于 ISO 时间(与 ISO Date 一致)和时差的方法,然后使用这些函数.

该函数为结束时间构建一个日期,以便计算可以使用日期方法。

// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
  Date.prototype.toISOTime = function() {
    return this.getUTCHours() + ':' + 
           ('0' + this.getUTCMinutes()).slice(-2) + ':' +
           ('0' + this.getUTCSeconds()).slice(-2) + '.' +
           ('00' + this.getUTCMilliseconds()).slice(-3) + 'Z';
  }
}

// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
  Date.prototype.timeDiff = function(date2) {
    var diff = Math.abs(this - date2);
    var sign = this > date2? '+' : '-';
    return sign + (diff/3.6e6|0) + ':' +                   // hours
           ('0' + ((diff%3.6e6)/6e4|0)).slice(-2) + ':' +  // minutes
           ('0' + ((diff%6e4)/1e3|0)).slice(-2) + '.' +    // seconds
           ('00' + (diff%1e3)).slice(-3);                  // milliseconds
  }
}

function countDown() {
  var now = new Date();
  var limitHr  = 1;
  var limitMin = 10;
  var limitDate = new Date(+now);
  // Set limitDate to next limit time
  limitDate.setUTCHours(limitHr, limitMin, 0, 0);
  var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
  var diff;

  // If outside limitHr:limitMin to (limitHr + 1):00
  if (now.getUTCHours() != limitHr || now.getUTCMinutes() != limitMin) {
    if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
    msg.push(now.timeDiff(limitDate));
  } else {
    msg.push('It\'s after ' + limitHr + ':' + ('0'+limitMin).slice(-2));
  }
  document.getElementById('msgDiv2').innerHTML = msg.join('<br>');
}

window.onload = function() {
 setInterval(countDown, 1000);
}
<div id="msgDiv2"></div>>

我保留了毫秒,如果您愿意的话,可以四舍五入到秒。

我已经使用 setInterval 保留计时器,但我更喜欢使用 setTimeout 并手动计算下一整秒之后的时间,以便它永远不会跳过。大多数使用 setTimeout 的浏览器都会慢慢漂移,以至于时不时地跳过一秒。除非您碰巧看到它,或者将它与系统时钟的滴答声进行比较,否则这并不是真正的问题。

关于javascript - 每日倒计时器 - 在 21 :57 显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37288527/

相关文章:

javascript - wrapAll 不换行纯文本

JavaScript 字符串不变性

c# - 从 javascript 调用 asp.net 页面方法不起作用

java - 在间隔的随机分钟内运行程序

Java一次性定时器终止主要功能

javascript - 如何在用户向下或向上滚动超过某个点后自动滚动到下一页/上一页

Java渲染循环和逻辑循环

C++将时间字符串转换为纪元的秒数

java - 监听器和计时器之间的通信

java - 为什么每次我激活此计时器时此变量都会不断重置?