我是JavaScript新手。我運行我的代碼,根據輸入計算用戶已經存活的時間。如果您希望看到代碼運行,則可以在我的課程測試服務器上獲得,代碼爲here。setInterval()無法正常工作
我的代碼的問題是setInterval()不能正常工作。根據我的理解,我的html頁面應該每隔1000ms(1s)更新一次,但是它不做任何更新。
我已經使用了setInterval()之前的一個類似的項目,顯示自Epoch以來的秒數,它工作正常。它更新了它應該的秒數。也許我的代碼中有其他東西不允許它工作?我已經通過jslint和jshint運行我的代碼,並且找不到我犯的錯誤。
在此先感謝!
function getUserBirthday(myEpoch) {
"use strict";
var unixEpoch = new Date()/1000.0;
var secondSince = unixEpoch - myEpoch;
var leftOrAlive = "";
if (secondSince < 0) {
leftOrAlive = ": Seconds Left";
secondSince = secondSince * -1;
} else {
leftOrAlive = ": Seconds Alive";
}
document.getElementById("secondsAlive").innerHTML = secondSince + leftOrAlive;
var years = secondSince/31556926;
secondSince = secondSince % 31556926;
var months = secondSince/2629743;
secondSince = secondSince % 2629743;
var days = secondSince/86400;
secondSince = secondSince % 86400;
var hours = secondSince/3600;
secondSince = secondSince % 3600;
var minutes = secondSince/60;
secondSince = secondSince % 60;
var seconds = secondSince;
//Convert Variables To String
years = years.toString();
months = months.toString();
days = days.toString();
hours = hours.toString();
minutes = minutes.toString();
seconds = seconds.toString();
//Remove Trailing Decimal Places
var yearStr = years.slice(0, (years.indexOf(".")));
var monthStr = months.slice(0, (months.indexOf(".")));
var dayStr = days.slice(0, (days.indexOf(".")));
var hourStr = hours.slice(0, (hours.indexOf(".")));
var minuteStr = minutes.slice(0, (minutes.indexOf(".")));
var secondStr = seconds.slice(0, (seconds.indexOf(".")));
//Show Results
document.getElementById("years").innerHTML = yearStr + ": Years";
document.getElementById("months").innerHTML = monthStr + ": Months";
document.getElementById("days").innerHTML = dayStr + ": Days";
document.getElementById("hours").innerHTML = hourStr + ": Hours";
document.getElementById("minutes").innerHTML = minuteStr + ": Minutes";
document.getElementById("seconds").innerHTML = secondStr + ": Second
}
function updateTimeSinceEpoch() {
"use strict";
var strDate = prompt("Enter your birthday: ex. November 12, 1996 00:00:00");
document.getElementById("birthday").innerHTML = strDate;
var myDate = new Date(strDate); // Your timezone!
var myEpoch = myDate.getTime()/1000.0;
var runFunction = getUserBirthday(myEpoch);
setInterval(runFunction, 1000);
}
getUserBirthday的最後一行出現語法錯誤。 – Blauharley