Javascript 如何定期更新时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5091888/
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
how to update time regularly?
提问by alex
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
return f_date;
}
<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>
alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page?
警报(现在);每秒给我一个值,但它没有在 html 中更新。如何在不刷新页面的情况下更新 html 上的时间?
回答by Ivo Wetzel
There are a number of mistakes in your code. Without the use of var
infront of your variable declarations, you leak them into the global scope.
您的代码中有许多错误。如果没有在var
变量声明前使用,就会将它们泄漏到全局作用域中。
Also, the use of document.write
is discouraged.
此外,使用的document.write
就是鼓励。
Here's how I would do it:
这是我将如何做到的:
JavaScript:
JavaScript:
function updateClock() {
var now = new Date(), // current date
months = ['January', 'February', '...']; // you get the idea
time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
// a cleaner way than string concatenation
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
document.getElementById('time').innerHTML = [date, time].join(' / ');
// call this function again in 1000ms
setTimeout(updateClock, 1000);
}
updateClock(); // initial call
HTML:
HTML:
<div id="time"> </div>
回答by Aaron Votre
setInterval(expression, timeout);
setInterval(表达式,超时);
The function setTimeout is intended for a single timeout, so using setInterval would be a more appropriate option. SetInterval will run regularly without the additional lines that Ivo's answer has.
函数 setTimeout 用于单个超时,因此使用 setInterval 将是更合适的选项。SetInterval 将定期运行,而不会像 Ivo 的答案那样添加额外的行。
I would rewrite Ivo's answer as follows:
我将伊沃的答案改写如下:
JavaScript:
JavaScript:
function updateClock() {
// Ivo's content to create the date.
document.getElementById('time').innerHTML = [date, time].join(' / ')
}
setInterval(updateClock, 1000);
Try it out yourself! https://jsfiddle.net/avotre/rtuna4x7/2/
回答by soloproper
Straigt Javascript time format / update
Straight Javascript 时间格式/更新
1: create month converter func 2: create time func 3: create update func 4: create outPut func
1:创建月份转换函数 2:创建时间函数 3:创建更新函数 4:创建输出函数
// month converter from index / 0-11 values
function covertMonth(num){
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// look into index with num 0-11
let computedRes = months[num];
return computedRes;
}
// time func
function Time(){
// important to get new instant of the Date referrance
let date = new Date();
this.time = date.toLocaleTimeString();
this.year = date.getUTCFullYear();
this.day = date.getUTCDate();
this.month = date.getUTCMonth();
this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year;
return this.currentTime;
}
function timeOutPut(){
let where = document.getElementById('some-id');
where.textContent = Time(); // 1:21:39 AM Dec 17 2017
}
// run every 5secs
setInterval(timeOutPut, 5000);
回答by Pranesh Janarthanan
I used @soloproper setInterval concept @Ivo Wetzel overall answer, my update is all about formatting the time as required. Reduced Programming Lines
我使用了@soloproper setInterval 概念@Ivo Wetzel 整体答案,我的更新都是关于根据需要格式化时间。减少编程线
<div id="liveClock"> </div>
$(document).ready(function () {
updateClock();
});
function updateClock() {
document.getElementById('liveClock').innerHTML = new Date().format("dd/MMMM/yyyy hh:mm:ss tt");
}
setInterval(updateClock, 1000);
回答by Yunus Eren Güzel
x = document.getElementsByTagName('SPAN').item(0);
x.innerHTML = f_date;
try putting this code block instead of return
statement, i haven't test it but it will probably work
尝试使用此代码块而不是return
语句,我还没有对其进行测试,但它可能会起作用
回答by Tim Reddy
There may be something in timeago jQuery plugin you can hook into, but I haven't honestly tried...
您可以使用 timeago jQuery 插件中的某些内容,但我还没有诚实地尝试过...
回答by BenWells
I think your setTmeout function has the wrong variables, the first one should be a function not a string, that confused me for a bit. Basically you need to write to the span tag when you run the function.
我认为你的 setTmeout 函数有错误的变量,第一个应该是一个函数而不是一个字符串,这让我有点困惑。基本上,您需要在运行该函数时写入 span 标记。
I created a jQuery version in a fiddle to demonstrate what I mean. Didn't have your strMonth function but you get the idea. I also changed the alert to console.log but you can remove that line.
我在小提琴中创建了一个 jQuery 版本来演示我的意思。没有你的 strMonth 函数,但你明白了。我还将警报更改为 console.log,但您可以删除该行。
回答by Rafay
$('span.foo').html(f_date);
place this inside your timeclock()
function
把它放在你的timeclock()
函数中
untested
未经测试
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
$('span.foo').html(f_date);
}
回答by Abderrahmane TAHRI JOUTI
I'd use setInterval rather than setTimeout:
我会使用 setInterval 而不是 setTimeout:
回答by Tom Gullen
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
document.getElementById("foo").innerHTML = f_date;
}
<span id="foo"></span>