var count = 24000,
running = true,
secondsNode = document.getElementById("seconds"),
millisecondsNode = document.getElementById("milliseconds"),
mOld,
mNew;
function draw() {
if (count > 0 && running) {
requestAnimationFrame(draw);
mNew = new Date().getTime();
count = count - mNew + mOld;
count = count >= 0 ? count : 0;
mOld = mNew;
secondsNode.innerHTML = Math.floor(count / 1000);
millisecondsNode.innerHTML = count % 1000;
}
}
mOld = new Date().getTime();
draw();
window.addEventListener("keydown", function(e) {
switch (e.keyCode) {
case 32: // PLAY
if (running) {
running = false;
} else {
running = true;
mOld = new Date().getTime();
draw();
}
break;
case 82: // RESET
count = 24000;
secondsNode.innerHTML = 24;
millisecondsNode.innerHTML = 0;
running = false;
}
});<p><span id="seconds">4</span> secs and <span id="milliseconds">000</span> milliseconds</p>
这是定时器的代码。这里发生的是计时器从24秒开始到0结束。但我需要的是启动这个计时器,从0到4秒。我们能做到吗?如果是这样,请帮助我。谢谢:)
发布于 2019-01-31 14:07:37
为此,您需要使用以下命令将时间递减器更改为递增器:
count = count + mNew - mOld;此外,您还需要确保在到达4000而不是0时停止您的条件和检查。
请参见下面的工作示例:
var count = 0,
running = false,
secondsNode = document.getElementById("seconds"),
millisecondsNode = document.getElementById("milliseconds"),
mOld,
mNew;
function isElementInViewport(el) { // run function to check if the element is in the viewport
var rect = el.getBoundingClientRect();
return rect.bottom > 0 && rect.right > 0 && rect.left < (window.innerWidth || document.documentElement.clientWidth) && rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
window.addEventListener('scroll', function() { // everytime we scroll
if(isElementInViewport(secondsNode)) { // check if the p element is on the screen - if it is then:
running = true; // start the timer (unpause it)
mOld = new Date().getTime();
draw();
} else { // if the element is off the screen then
running = false; // pause the timer
}
});
function draw() {
if (count < 4000 && running) { // change to check count < 4000 to keep running
requestAnimationFrame(draw);
mNew = new Date().getTime();
count = count + mNew - mOld; // change to increment the count
count = count >= 4000 ? 4000 : count; // change stop the clock from incrementing
mOld = mNew;
secondsNode.innerHTML = Math.floor(count / 1000);
millisecondsNode.innerHTML = count % 1000;
}
}
window.addEventListener("keydown", function(e) {
switch (e.keyCode) {
case 32: // PLAY (space)
if (running) {
running = false;
} else {
running = true;
mOld = new Date().getTime();
draw();
}
break;
case 82: // RESET (r)
count = 0;
secondsNode.innerHTML = 0;
millisecondsNode.innerHTML = 0;
running = true;
}
});.other {
padding-bottom: 100vh;
}<div class="other"></div>
<p><span id="seconds">4</span> secs and <span id="milliseconds">000</span> milliseconds</p>
<div class="other"></div>
https://stackoverflow.com/questions/54454185
复制相似问题