每秒更新javascript时间

时间:2014-10-27 09:13:05

标签: javascript datetime

基本上我想要一个活动时钟,每秒更新一次!我环顾四周,无法找到有效的东西。这是我尝试过的:

function doDate()
{
    var str = "";

    var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

    var now = new Date();

    str += "Today is: " + days[now.getDay()] + ", " + now.getDate() + " " + months[now.getMonth()] + " " + now.getFullYear();
    var updateTime = function() { setTimeout("doDate()", 1000); }

    document.getElementById("todaysDate").innerHTML = str;
}

这似乎不起作用!我认为我在这里做过一些事情吗?

5 个答案:

答案 0 :(得分:2)

这行代码无效:

var updateTime = function() { setTimeout("doDate()", 1000); }

定义函数变量updateTime,使doDate的调用被推迟,但此变量在代码中未使用。

而不是这个,你必须立即调用setTimeout而不用函数包装它:

setTimeout(doDate, 1000);

答案 1 :(得分:1)

请修改您的代码,如下所示: -

function doDate()
{
    var str = "";

    var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

    var now = new Date();

    str += "Today is: " + days[now.getDay()] + ", " + now.getDate() + " " + months[now.getMonth()] + " " + now.getFullYear() + " " + now.getHours() +":" + now.getMinutes() + ":" + now.getSeconds();
    document.getElementById("todaysDate").innerHTML = str;
}

setInterval(doDate, 1000);
<div id="todaysDate"></div>

答案 2 :(得分:0)

您的setTimeout调用不正确:

var updateTime = function() { setTimeout("doDate()", 1000); }

应该看起来像:

setTimeout(doDate, 1000);

添加回调时,不应该调用该函数(在这种情况下,不应将其添加为字符串),添加函数本身。
并且不需要将其包装在其中的函数,只需立即调用setTimeout函数。

答案 3 :(得分:0)

以下代码可能对您有所帮助

function doDate()
{
    var str = "";
    var now = new Date();
    str = now.toDateString() +' '+now.toLocaleTimeString() ;
    document.getElementById("todaysDate").innerHTML = str;
}
setInterval(doDate, 1000);

答案 4 :(得分:0)

function doDate() {
  let currentDate = document.getElementById('currentDate');
  let current = new Date();
  currentDate.innerHTML = `Current Date and Time : <b>${current}</b> `;
}

setInterval(doDate, 1000);
<div id="currentDate"></div>