gpt4 book ai didi

javascript - 通过 Date() 显示时间 : it is not being updated using setInterval()

转载 作者:行者123 更新时间:2023-12-02 14:42:04 25 4
gpt4 key购买 nike

我有这个代码来用西类牙语显示时间和一些日期信息:

  var date = new Date();

var hour = date.getHours().toString();
var minutes = date.getMinutes().toString();

var day = date.getDate();

switch (date.getMonth()) {
case 0:
month = "Ene";
break;
case 1:
month = "Feb";
break;
case 2:
month = "Mar";
break;
case 3:
month = "Abr";
break;
case 4:
month = "May";
break;
case 5:
month = "Jun";
break;
case 6:
month = "Jul";
break;
case 7:
month = "Ago";
break;
case 8:
month = "Sep";
break;
case 9:
month = "Oct";
break;
case 10:
month = "Nov";
break;
case 11:
month = "Dic";
break;
}

if (hour.length == 1) {
hour = '0' + hour;
}
if (minutes.length == 1) {
minutes = '0' + minutes;
}
setInterval($('#hour').html('<b>' + hour + ':' + minutes + '<br>' + '<span class="day">' + day + ' ' + month + '</span></b>'), 60000);

当我加载文档时,它工作正常。问题是时间永远不会更新..为什么?

最佳答案

正如@Travis J 所指出的,setTimeout 第一个参数应该是一个函数。 (参见the doc。)

在您的情况下,您还希望此函数在每次调用时重新计算日期。

所以类似:

// Define a function that will update the html from current date
function updateDate() {
var date = new Date();

var hour = date.getHours().toString();
var minutes = date.getMinutes().toString();

var day = date.getDate();

switch (date.getMonth()) {
case 0:
month = "Ene";
break;
...
}

if (hour.length == 1) {
hour = '0' + hour;
}
if (minutes.length == 1) {
minutes = '0' + minutes;
}

// Update the page content
$('#hour').html('<b>' + hour + ':' + minutes + '<br>' + '<span class="day">' + day + ' ' + month + '</span></b>'
}

// Call the function the first time (setInterval will not call it right away)
updateDate();

// Schedule the function to be called every minute after that
setInterval(updateDate, 60000);

关于javascript - 通过 Date() 显示时间 : it is not being updated using setInterval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com