我是JavaScript的新手。我运行我的代码,根据输入计算用户活着的时间。如果您希望看到代码运行,可以在我的班级测试服务器here上找到它。
我的代码的问题是setInterval()无法正常工作。根据我的理解,我的html页面应该每隔1000毫秒(1秒)更新一次,但是它没有做任何事情,它不会更新。
我之前在一个类似的项目中使用了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);
}
答案 0 :(得分:2)
当你使用时:
var runFunction = getUserBirthday(myEpoch);
setInterval(runFunction, 1000);
runFunction
变量为undefined
,因为getUserBirthday()
方法不会返回任何内容。因此,使用此结构,您的函数将只执行一次:
function getUserBirthday(message) {
console.log(message);
}
var runFunction = getUserBirthday("Hello");
setInterval(runFunction, 1000);
尝试使用以下结构,它应该做的诀窍:
function getUserBirthday(message) {
console.log(message);
}
setInterval(function() {
getUserBirthday('Hello');
}, 1000);