Javascript 如何暂停和恢复计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12487352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I pause and resume a timer?
提问by esandrkwn
I got this function that starts a timer on this format 00:00:00 whenever I click on a button. But I don't know how to do functions resume and pause. I've found some snippets that I thought could be helpful but I couldn't make those work. I'm new to using objects in js.
我得到了这个功能,每当我点击一个按钮时,它就会以这种格式 00:00:00 启动一个计时器。但我不知道如何恢复和暂停功能。我发现了一些我认为可能会有所帮助的片段,但我无法使这些片段起作用。我是在 js 中使用对象的新手。
function clock() {
var pauseObj = new Object();
var totalSeconds = 0;
var delay = setInterval(setTime, 1000);
function setTime() {
var ctr;
$(".icon-play").each(function () {
if ($(this).parent().hasClass('hide')) ctr = ($(this).attr('id')).split('_');
});
++totalSeconds;
$("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds / 3600)));
$("#min_" + ctr[1]).text(pad(Math.floor((totalSeconds / 60) % 60)));
$("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds % 60)));
}
}
pad() just adds leading zeros
pad() 只是添加前导零
回答by Danil Speransky
I think it will be better if you will create clock object. See code (see Demo: http://jsfiddle.net/f9X6J/):
我认为如果您创建时钟对象会更好。见代码(见演示:http: //jsfiddle.net/f9X6J/):
var Clock = {
totalSeconds: 0,
start: function () {
var self = this;
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(Math.floor(self.totalSeconds / 3600));
$("#min").text(Math.floor(self.totalSeconds / 60 % 60));
$("#sec").text(parseInt(self.totalSeconds % 60));
}, 1000);
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
}
};
Clock.start();
$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
回答by dcasadevall
Just clearing the interval wouldn't work, because totalSeconds would not get incremented. I would set up a flag that determines if the clock is paused or not.
仅仅清除间隔是行不通的,因为 totalSeconds 不会增加。我会设置一个标志来确定时钟是否暂停。
This flag would be simply set upon calling pause() or unset upon resume(). I separated the totalSeconds increase to a 'tick' timeout that will always be running, even when paused (so that we can keep track of the time when we resume).
该标志将在调用 pause() 时简单设置或在 resume() 时取消设置。我将 totalSeconds 增加分隔为一个“滴答”超时,该超时将始终运行,即使在暂停时也是如此(以便我们可以跟踪恢复的时间)。
The tick function will therefore only update the time if the clock is not paused.
因此,滴答功能只会在时钟未暂停时更新时间。
function clock()
{
var pauseObj = new Object();
var totalSeconds = 0;
var isPaused = false;
var delay = setInterval(tick, 1000);
function pause()
{
isPaused = true;
}
function resume()
{
isPaused = false;
}
function setTime()
{
var ctr;
$(".icon-play").each(function(){
if( $(this).parent().hasClass('hide') )
ctr = ($(this).attr('id')).split('_');
});
$("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds/3600)));
$("#min_" + ctr[1]).text(pad( Math.floor((totalSeconds/60)%60)));
$("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds%60)));
}
function tick()
{
++totalSeconds;
if (!isPaused)
setTime();
}
}
回答by xdazz
Use window.clearIntervalto cancel repeated action which was set up using setInterval()
.
使用window.clearInterval取消使用setInterval()
.
clearInterval(delay);
回答by VRN
<html>
<head><title>Timer</title>
<script>
//Evaluate the expression at the specified interval using setInterval()
var a = setInterval(function(){disp()},1000);
//Write the display() for timer
function disp()
{
var x = new Date();
//locale is used to return the Date object as string
x= x.toLocaleTimeString();
//Get the element by ID in disp()
document.getElementById("x").innerHTML=x;
}
function stop()
{
//clearInterval() is used to pause the timer
clearInterval(a);
}
function start()
{
//setInterval() is used to resume the timer
a=setInterval(function(){disp()},1000);
}
</script>
</head>
<body>
<p id = "x"></p>
<button onclick = "stop()"> Pause </button>
<button onclick = "start()"> Resume </button>
</body>
</html>