Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start-stop-reset simple timer using jQuery

Tags:

jquery

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

like image 334
Ryan Barnaby Avatar asked Feb 15 '23 23:02

Ryan Barnaby


1 Answers

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);
}
like image 175
Vishal Avatar answered Jun 25 '23 03:06

Vishal