如何从头开始制作时钟对象(Javascript)

How to make a Clock Object from Scratch (Javascript)

本文关键字:对象 Javascript 时钟 从头开始      更新时间:2023-09-26

我想使用 get 方法(即 gethour、getminute、getsecond 从 java 脚本)制作一个时钟对象,并知道如何做到这一点?

如果我创建一个带有变量小时、分钟和秒的对象,我如何让它们有问题地更新它们。

我只想创建一个时钟来设置时间和显示时间。

// JavaScript Document
 function updateTime() { 
    // get all parts of the current time
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    if(hours < 10){
        hours = " " + hours
        }
    if(minutes < 10){
        minutes = "0" + minutes
        }
    if(seconds < 10){
        seconds = "0" + seconds
        } 
    // splice them together into a character string named "currentTime"
    var currentTime = hours + ':' + minutes + ':' + seconds;    
    // get the clock div 
    var myClock = document.getElementById('clock');
    // write the currentTime string to the clock div
    myClock.innerHTML = currentTime;
    setTimeout("updateTime()", 1000)
}
function clock(){
    var time = new Date()
    var hr = time.getHours()
    var min = time.getMinutes()
    var sec = time.getSeconds()
    var ampm = " PM "
    if (hr < 12){
    ampm = " AM "
        }
    if (hr > 12){
    hr -= 12
        }
    if (hr < 10){
    hr = " " + hr
        }
    if (min < 10){
    min = "0" + min
        }
    if (sec < 10){
    sec = "0" + sec
        }
     // splice them together into a character string named "currentTime"
    var currentTime = hr + ":" + min + ":" + sec + ampm;    
    // get the clock div 
    var myClock = document.getElementById('clock12');
    // write the currentTime string to the clock div
    myClock.innerHTML = currentTime;
    setTimeout("clock()", 1000)
}
function setClock(){
    var time = new Date()
    var hr = time.getHours()
    var min = time.getMinutes()
    var sec = time.getSeconds()
    var ampm = " PM "
    if (hr < 12){
    ampm = " AM "
        }
    if (hr > 12){
    hr -= 12
        }
    if (hr < 10){
    hr = " " + hr
        }
    if (min < 10){
    min = "0" + min
        }
    if (sec < 10){
    sec = "0" + sec
        }
     // splice them together into a character string named "currentTime"
    var currentTime = hr + ":" + min + ":" + sec + ampm;    
    // get the clock div 
    var myClock = document.getElementById('setClock');
    // write the currentTime string to the clock div
    myClock.innerHTML = currentTime;
    setTimeout("setClock()", 1000)
}

如果不使用 Date 对象,就无法让时钟显示"实时"时间。但是如果你只是想为一个游戏或相对的东西制作一个任意时钟,你可以做这样的事情:

var clock = {
  hours: 0,
  minutes: 0,
  seconds: 0
}
function updateTime(part, max) {
  return function(){
    clock[part]++
    if (clock[part] > max) clock[part] = 0
  }
}
setInterval(updateTime('hours', 24), 60*60*1000)
setInterval(updateTime('minutes', 60), 60*1000)
setInterval(updateTime('seconds', 24), 1000)