我有一個腳本,在瀏覽器的右上角用當前日期和時間創建一個欄。我試圖每隔三十秒更新一次,以便保持現場時間,而不僅僅是加載頁面的時間。您會看到我使用set_time()函數onload創建了時間欄,然後創建一個旨在調用timer()的setInterval,後者又通過再次調用set_time()函數來更新時間。計時器清楚地觸發,因爲每4秒鐘我都會收到一個帶有「hi」(來自timer()函數)的警告框,但是在此之後它應該調用set_time()時,它不起作用。我應該在每次啓動定時器時都會收到「set time」(位於set_time()函數末尾)的警報,而我不這樣做。任何人都可以幫忙嗎?setInterval無法與特定功能
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);
}
您是否在瀏覽器控制檯中發現任何錯誤? – lonesomeday