使用 jQuery 启动-停止-重置简单计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19400995/
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
start-stop-reset simple timer using jQuery
提问by Ryan Barnaby
I have a code that looks like this
我有一个看起来像这样的代码
JS
JS
var counter = 0;
var timer = setInterval("tictac()", 1000);
function tictac(){
counter++;
$("#clock").html(counter);
}
HTML
HTML
<div id="clock">0</div>
<div id="buttons" class="clear">
<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>
</div>
How can I make use of the buttons to control the timer, start counting up when startbutton is pressed, stop counting when stopbutton is pressed and reset counter when resetbutton is pressed.
如何使用按钮来控制计时器,按下开始按钮时开始计数,按下停止按钮时停止计数,按下重置按钮时重置计数器。
Can someone help?
有人可以帮忙吗?
I managed to do this
我设法做到了
$(document).ready(function($) {
var timer = undefined;
$('#start').on('click', function(){
timer = window.setInterval('tictac()', 1000);
});
$('#pause').on('click', function(){
window.clearInterval(timer);
});
$('#reset').on('click', function(){
timer = window.clearInterval(timer);
});
});
var counter = 0;
function tictac(){
counter++;
$("#clock").html(counter);
}
The start and the stop buttons do the work, but the reset won't work, can some one check what's wrong with the code? pretty please
开始和停止按钮可以工作,但重置不起作用,有人可以检查代码有什么问题吗?漂亮请
回答by Vishal
try http://jsfiddle.net/vishalgupta358/DkTWN/
试试http://jsfiddle.net/vishalgupta358/DkTWN/
var counter = 0;
var timer = null;
function tictac(){
counter++;
$("#clock").html(counter);
}
function reset()
{
clearInterval(timer);
counter=0;
}
function startInterval()
{
timer= setInterval("tictac()", 1000);
}
function stopInterval()
{
clearInterval(timer);
}
回答by Ryan Barnaby
Nailed the solution
解决了
$('#reset').on('click', function(){
counter = -1;
tictac();
window.clearInterval(timer);
});
回答by david
You can utilize onclick
to your button. For example: <button onclick="tictac()">
. For further explanation, you can see this link. There has a demo that will solve your problem. Also, you can view the source code.
您可以使用onclick
您的按钮。例如:<button onclick="tictac()">
。如需进一步说明,您可以查看此链接。有一个演示可以解决您的问题。此外,您可以查看源代码。