Reputation: 169
I have a code that looks like this
JS
var counter = 0;
var timer = setInterval("tictac()", 1000);
function tictac(){
counter++;
$("#clock").html(counter);
}
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 start button is pressed, stop counting when stop button is pressed and reset counter when reset button 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
Upvotes: 4
Views: 26530
Reputation: 169
Nailed the solution
$('#reset').on('click', function(){
counter = -1;
tictac();
window.clearInterval(timer);
});
Upvotes: 1
Reputation: 3218
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.
Upvotes: 0
Reputation: 256
try 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);
}
Upvotes: 7