4

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

2
  • why the "timer = window.clearInterval(timer);" won't do the job, what am I doing wrong? Commented Oct 16, 2013 at 15:15
  • Don't pass the function inside quotes to setInterval() some browsers refuse to do that now. Commented Oct 17, 2013 at 14:45

3 Answers 3

7

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

sorry I didn't mentioned, I would like to control the timer using jQuery selectors
bind the functions to the buttons on page load
This fiddle link is dead, Can you post another one please!!
1

Nailed the solution

$('#reset').on('click', function(){
    counter = -1;
    tictac();
    window.clearInterval(timer);
});

Comments

0

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.

1 Comment

I forgot to mention, I want to control the timer using jQuery selectors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.