Nick Zink Nick Zink - 3 months ago 10
HTML Question

Start and Stop timer not working

I am trying to make a timer that starts when you click the top button and stops and resets when you click the bottom button. Here is a link to my fiddle http://www.jsfiddle.net/AbrGL/

My HTML:

<input type="submit" id="start-clock" value="Click here to start timer" name="submit" onClick="startclock()"/>
<div id="timer">0</div>
<input type="submit" id="stop-clock" value="Click here to stop and reset the timer" name="submit" onClick="stopclock()"/>


My JavaScript:

function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
}
else if (clicked === true) {
}
}
function stopWatch() {
sec+;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML=0;
clicked = false;
}

Answer

Ok you have a lot of typos.

First, sec+; does not do anything. It should be sec++;.

Second, your onClick properties point to startclock() and stopclock(), which should actually be startClock() and stopClock(). Function names are case-sensitive in JavaScript.

Third, the clicked variable is undefined so startClock() will never actually do anything. Add var clicked = false; before your function declarations.

Last but not least, sec is undefined, so incrementing it doesn't make sense. Add var sec = 0; before your function declarations.

HTML should look like

<input type="submit" id="start-clock" value="Click here to start timer" name="submit" onClick="startClock()"/>

<div id="timer">0</div>

<input type="submit" id="stop-clock" value="Click here to stop and reset the timer" name="submit" onClick="stopClock()"/>

and JavaScript should look like

var clicked = false;
var sec = 0;

function startClock() {
    if (clicked === false) {
        clock = setInterval("stopWatch()", 1000);
        clicked = true;
    }
    else if (clicked === true) {
    }
}

function stopWatch() {
    sec++;
    document.getElementById("timer").innerHTML = sec;
}

function stopClock() {
    window.clearInterval(clock);
    sec = 0;
    document.getElementById("timer").innerHTML=0;
    clicked = false;
}

Here is a working fiddle with the changes above: http://jsfiddle.net/AbrGL/8/