当用户在 JavaScript 中选择新时间时,继续单击时钟

Continue a clicking clock when user chooses new time in JavaScript

本文关键字:时间 继续 时钟 单击 用户 JavaScript 新时间 选择      更新时间:2023-09-26

我在使用Vanilla Javascript构建时钟时遇到了一个问题。 我得到的当前时间很好,但我希望用户能够设置自己的时间。用户想要的时间从三个输入字段中获取,并作为可选的参数(updateH,updateM,updateS)传递给下面的函数:

function updateTime(updateH,updateM,updateS){
    updateH = updateH || false; updateM = updateM || false; updateS = updateS || false;
    today = new Date();
    if (updateH != false || updateM != false || updateS != false) {
        today.setHours(updateH);
        today.setMinutes(updateM);
        today.setSeconds(updateS);
    }
    h = addLeadingZeroes(today.getHours());     //Today's time (hours)
    m = addLeadingZeroes(today.getMinutes());   //Today's time (minutes)
    s = addLeadingZeroes(today.getSeconds());   //Today's time (seconds)
    day = getDay().toUpperCase();               //Today's date (day)
    date = today.getaDmante();                  //Today's date (date)
    month = getMonth().toUpperCase();           //Today's date (month)
    time24H = h + ":" + m + ":" + s;
    drawWatch();
    setTimeout(updateTime, 1000);
}
updateTime();

此功能每秒运行一次(1000ms),因此时钟在一秒后重置为当前时间,使用户选择的时间消失。

有没有办法将时间更新到用户传递的时间,然后使用新时间继续时钟滴答作响?例如:

时钟显示"12:00:00",然后用户输入时间"13:30:00",现在时钟从"13:30:01...13:30:

02....13:30:03...ETC"开始继续滴答作响。

非常感谢您的帮助!

当用户设置他们的时间时,计算他们的时间和当前时间之间的差值,存储此值。然后,每次您要重绘手表时,只需获取新的当前时间,减去存储的差异并重新绘制手表。

就我个人而言,我会创建一个名为"Watch"的新原型,并在此对象中执行您想要的所有操作。

/* Create a "Watch" prototype */
function Watch(hours, minutes, seconds, drawInterval){
  var t = this;
  this.offset = 0;
  this.drawInterval = drawInterval || 1000;
  this.setTime = function(hours, minutes, seconds){
    var now = new Date().getTime();
    var theirTime = new Date();
    if(hours) theirTime.setHours(hours);
    if(minutes) theirTime.setMinutes(minutes);
    if(seconds) theirTime.setSeconds(seconds);
    this.offset = now - theirTime.getTime();
  };
  this.getTime = function(){
    var d = new Date( new Date() - this.offset );
    return d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
  };
  this.draw = function(elementID){
    function draw(){
      
      document.getElementById(elementID).innerHTML = t.getTime();
      setTimeout(draw, t.drawInterval);
    };
    draw();
  };
  this.setTime(hours, minutes, seconds); // Initialize
}
/* Create an instance of the "Watch" prototype */
var W = new Watch();
/* Draw the watch to the DOM */
W.draw("watch");
/* Set the Users Time */
W.setTime(12,45,30); // 12:45:30
<div id='watch'></div>