【发布时间】:2016-02-18 08:19:13
【问题描述】:
我正在尝试在 JavaScript 中创建一个倒数计时器,特别是我可以设置为一两分钟以及它何时开始的倒数计时器。
这是我从头开始就能完成的,但我似乎无法让它发挥作用:
var tim = 90
var min = (tim / 60) >> 0;
var sec = tim % 60;
function set1() {
tim=60;
}
function set2() {
tim=120;
}
function start() { function{ setInterval(function(){ tim-1; }, 1000);
}
function display() {
document.getElementById("demo").innerHTML = min + ":" + sec ;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="display()">
<p id="demo"></p>
<button onclick="set1()"> set one minute</button>
<button onclick="set2()"> set two minute</button>
<button onclick="start()"> start </button>
</body>
</html>
我也尝试从here, 调整以下解决方案,但是 无济于事。
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body>
我在这里错过了什么?
【问题讨论】:
-
需要注意的一点是,您的函数中有
tim-1;,您将其传递给setInterval。您正在评估表达式,但您没有对结果做任何事情。你可能打算做tim = tim-1;
标签: javascript html timer