我有一个脚本,可以在浏览器的右上角创建一个带有当前日期和时间的栏。我试图每三十秒更新一次,以便它保持实时,而不仅仅是页面加载的时间。您会看到我使用 set_time() 函数 onload 创建了时间条,然后创建了一个 setInterval 来调用 timer(),而 timer() 又通过再次调用 set_time() 函数来更新时间。计时器显然正在触发,因为每 4 秒我都会收到一个带有“hi”的警报框(来自 timer() 函数),但是当它应该在此之后调用 set_time() 时它不起作用。每次触发计时器时,我都应该收到带有“设置时间”的警报(位于 set_time() 函数的末尾),但我没有。有人可以帮忙吗?
window.onload = function(){
set_time();
window.setInterval(timer, 4000);
};
function timer(){
alert('hi');
set_time();
}
function set_time(){
//create date object to manipulate
var d = new Date();
//current day of the week
var d_names= new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
curr_day = d.getDay();
//current date
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
//current Time
var a_p = "";
var curr_hour = d.getHours();
if (curr_hour < 12)
{
a_p = "a.m.";
}
else
{
a_p = "p.m.";
}
if (curr_hour == 0)
{
curr_hour = 12;
}
if (curr_hour > 12)
{
curr_hour = curr_hour - 12;
}
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
{
curr_min = "0" + curr_min;
}
element = document.getElementById('dateTime');
if(element){
//if dateDiv already exists, update contents
dateDiv.innerHTML = '';
dateDiv.innerHTML = '<p>' + d_names[curr_day] + ', ' + m_names[curr_month] + ' ' + curr_date + ', ' + curr_year + ' | ' + '<strong>' + curr_hour + ':' + curr_min + ' ' + a_p + '</strong>' + '</p>';
}
else{
//else create new dateDiv and append it to DOM body
var dateDiv = document.createElement('div');
dateDiv.innerHTML = '<p>' + d_names[curr_day] + ', ' + m_names[curr_month] + ' ' + curr_date + ', ' + curr_year + ' | ' + '<strong>' + curr_hour + ':' + curr_min + ' ' + a_p + '</strong>' + '</p>';
dateDiv.id = 'dateTime';
document.body.appendChild(dateDiv);
}
alert('set time');
//setTimeout("set_time()", 3000);
}