我正在制作一款 ZORK 风格的游戏,它有持续的警报和提示,并且包括你需要坚持才能获胜的时间。
由于它有玩游戏的警报和提示,我无法使用设置的超时来运行时钟,因此我创建了一个基于实时的时钟,但在让它工作时遇到了一些麻烦。
这是代码
var now = new Date();
var stS = now.getSeconds();
var stM = now.getMinutes();
var stH = now.getHours();
function getElapsedTime() {
setTimeout(function () {
var reS = now.getSeconds();
var reM = now.getMinutes();
var reH = now.getHours();
var elapS = reS - stS;
var elapM = reM - stM;
var elapH = reH - stH;
if (elapM < 0) {
reM = reM + 60;
elapM = reM - stM;
}
if (elapS < 0) {
reS = reS + 60;
elapS = reS - stS;
}
alert(elapS);
alert(elapM);
alert(elapH);
}, 10000);
}
getElapsedTime();
编辑: 我在 jsfiddle 中运行它,但它返回警报说没有时间过去,而它应该说已经过去了十秒。 http://jsfiddle.net/t57wsrx8/
最佳答案
您现在使用的与 10 秒前开始时的相同。
Date
对象保留给定的时间。它不会随着时间的推移而自动改变。您需要实例化一个新的now
:
function getElapsedTime() {
setTimeout(function () {
var now = new Date();
var reS = now.getSeconds();
var reM = now.getMinutes();
var reH = now.getHours();
var elapS = reS - stS;
var elapM = reM - stM;
var elapH = reH - stH;
if (elapM < 0) {
reM = reM + 60;
elapM = reM - stM;
}
if (elapS < 0) {
reS = reS + 60;
elapS = reS - stS;
}
alert(elapS);
alert(elapM);
alert(elapH);
}, 10000);
}
请注意,如果将日期视为数字,则可以更清晰地计算时间跨度:
var start = +new Date();
function getElapsedTime() {
setTimeout(function () {
var elapsed = +new Date() - start;
var elapS = Math.floor(elapsed / 1000) % 60;
var elapM = Math.floor(elapsed / 60000) % 60;
var elapH = Math.floor(elapsed / 3600000) % 24;
alert(elapS);
alert(elapM);
alert(elapH);
}, 10000);
}
getElapsedTime();
关于javascript - 基于实时时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29308685/