简体   繁体   English

如何使用时钟重复JavaScript函数

[英]How to repeat a javascript function with a clock

I am just starting to learn javascirpt and I'm trying to make my own clock widget. 我刚刚开始学习javascirpt,并且正在尝试制作自己的时钟小部件。 It seems when I use the "ourDate.toLocalString()" it only displays the time as it was when the function was called. 似乎当我使用“ ourDate.toLocalString()”时,它仅显示调用该函数时的时间。 So I figured I would have to repeat the function continuously for each second in order for it to continuously keep the current time. 因此,我想我必须连续不断地每秒重复一次此功能,以使其连续保持当前时间。 But the problem I have is when I start the script, it repeats the function only one time. 但是我遇到的问题是,当我启动脚本时,它仅重复执行一次该函数。 What am I doing wrong? 我究竟做错了什么? Below is the code: 下面是代码:

function updateclock(){
ourDate = new Date();
document.write(ourDate.toLocaleString());
}

function startclock() {
updateclock();
setInterval("updateclock()", 1000); 
}

The problem is document.write . 问题是document.write If you call that after the document has loaded, it will overwrite the whole document , including your startclock function, that cannot be called anymore. 如果在文档加载后调用它,它将覆盖整个文档 ,包括您的startclock函数,该文档将无法再调用。

Update the content of an HTML element instead: 更新HTML元素的内容:

<div id="clock"></div>
<script type="text/javascript">
function updateclock(){
    ourDate = new Date();
    document.getElementById("clock").innerHTML = ourDate.toLocaleString();
}

function startclock() {
    updateclock();
    setInterval(updateclock, 1000); 
}
startclock();
</script>

http://jsfiddle.net/Ys87F/ http://jsfiddle.net/Ys87F/

Also: do not pass a string to setInterval (or setTimeout ), pass the function name instead. 另外:不要将字符串传递给setInterval (或setTimeout ),而应传递函数名称。

您要改为执行此操作:

setInterval(updateclock, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM