Javascript 如何让Javascript时间自动更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10470825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:27:50  来源:igfitidea点击:

How to make Javascript time automatically update

javascript

提问by jameswildi

I am using the following Javascript code to display the time on my website. How can I make this update automatically.

我正在使用以下 Javascript 代码在我的网站上显示时间。如何自动进行此更新。

Thanks

谢谢

<section class="portlet grid_6 leading"> 
<header>
<h2>Time<span id="time_span"></span></h2>
</header>
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
    minutes = "0" + minutes
}
var t_str = hours + ":" + minutes + " ";
if(hours > 11){
    t_str += "PM";
} else {
   t_str += "AM";
}
document.getElementById('time_span').innerHTML = t_str;
</script>
</section>

回答by UltraInstinct

Use setTimeout(..)to call a function after a specific time. In this specific case, it is better to use setInterval(..)

使用setTimeout(..)在特定时间后调用函数。在这种特定情况下,最好使用setInterval(..)



function updateTime(){
    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    if (minutes < 10){
        minutes = "0" + minutes
    }
    var t_str = hours + ":" + minutes + " ";
    if(hours > 11){
        t_str += "PM";
    } else {
        t_str += "AM";
    }
    document.getElementById('time_span').innerHTML = t_str;
}
setInterval(updateTime, 1000);

回答by Alexis Pigeon

Add all your javascript code in a function called updateClock()placed in the <head>section of your page, and alter the <body>tag that way:

将您所有的 javascript 代码添加到一个名为updateClock()放置在<head>页面部分中的函数中,并以<body>这种方式更改标签:

<body onload="updateClock(); setInterval('updateClock()', 1000 )">

It will recalculate and redisplay the time every second. Since you only display hours and minutes, you can use a longer interval. If you want to update time every numSecondsyou should use something like

它将每秒重新计算并重新显示时间。由于您只显示小时和分钟,您可以使用更长的时间间隔。如果你想更新时间,numSeconds你应该使用类似的东西

<body onload="updateClock(); setInterval('updateClock()', numSeconds * 1000 )">

And of course, this one is just one of many gazillions solutions that you can find out there.

当然,这只是您可以在那里找到的无数解决方案之一。

回答by Recognizer

There are plenty of clock libraries out there. Perhaps check out this previous post: How to create a jquery clock timer

那里有很多时钟库。也许可以查看之前的帖子:如何创建 jquery 时钟计时器

回答by Parth Thakkar

try this, a tidier version:

试试这个,一个更整洁的版本:

var el = document.getElementById('time_span')
setInterval(function() {

    var currentTime = new Date(),
        hours = currentTime.getHours(),
        minutes = currentTime.getMinutes(),
        ampm = hours > 11 ? 'PM' : 'AM';

    hours += hours < 10 ? '0' : '';
    minutes += minutes < 10 ? '0' : '';

    el.innerHTML = hours + ":" + minutes + " " + ampm;
}, 1000);

回答by KooiInc

A bit less messy would be:

少一点混乱是:

timer();

function timer(){
 var now     = new Date,
     hours   = now.getHours(),
     ampm    = hours<12 ? ' AM' : ' PM',
     minutes = now.getMinutes(),
     seconds = now.getSeconds(),
     t_str   = [hours-12, //otherwise: what's the use of AM/PM?
                (minutes < 10 ? "0" + minutes : minutes),
                (seconds < 10 ? "0" + seconds : seconds)]
                 .join(':') + ampm;
 document.getElementById('time_span').innerHTML = t_str;
 setTimeout(timer,1000);
}

The timer updates (roughly) every second (= 1000 Ms), using setTimeoutfrom within the timer function.

计时器(大致)每秒更新一次(= 1000 毫秒),使用setTimeout来自计时器功能。

?See it in action

?看到它在行动

回答by Satya Chandu

This code output format->00:00:00 and refresh automatically like real time clock, hope it works..

此代码输出格式->00:00:00 并像实时时钟一样自动刷新,希望它有效..

function r(txt) {
    document.write(tex);
}

function createTIME() {
    d = new Date();
    var time = addZERO(d.getHours()) + ':' + addZERO(d.getMinutes()) + ':' + addZERO(d.getSeconds());
    return 'Present Time = ' + time;
}

function doDyn() {
    document.getElementById('Dyn').innerHTML = createTIME();
}

function addZERO(val) {
    return ((val < 10) ? '0' : '') + val;
}

回答by Amornbordee

timer();

function timer(){
 var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var sec = currentTime.getSeconds()
if (minutes < 10){
    minutes = "0" + minutes
}
if (sec < 10){
    sec = "0" + sec
}
var t_str = hours + ":" + minutes + ":" + sec + " ";
if(hours > 11){
    t_str += "PM";
} else {
   t_str += "AM";
}
 document.getElementById('time_span').innerHTML = t_str;
 setTimeout(timer,1000);
}
<header>
<h2>Time<span id="time_span"></span></h2>
</header>