Gopala Krishnan
Gopala Krishnan

Reputation: 1

Timer work in javascript

In my project i am using timer which runs, when start button is clicked and stop when end is clicked

The problem is by mistake when start button is clicked double or more than once ..time takes +1000 millsec extra and start running faster ..this should no happen

My javascript is..

<script type="text/javascript">
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
    sec++;
    if (sec == 60) {
        sec = 0;
        min = min + 1; 
    } else {
       min = min; 
    }

    if (min == 60) {
       min = 0; 
       hour += 1; 
    }
    if (sec<=9) { sec = "0" + sec; }
    document.getElementById("starttime").innerHTML = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
    SD=window.setTimeout("stopwatch();", 1000);
}

function f3() {
    clearTimeout(SD);
}
</script>
<form name="clock">
<div id="starttime" style="font-size:large; "></div>
<input type="button" name="theButton" id="Start" value="Start"  onClick="stopwatch(this.value);" />
<input type="button" name="theButton" id="end" value="Stop"  onClick="f3();" />
</form>

I have tried something like this..

  if (document.clock.theButton.value == "Start") {
            window.clearTimeout(SD);
            return true;  }`

.... but its not working

Upvotes: 0

Views: 289

Answers (2)

Teemu
Teemu

Reputation: 23416

You can do something like this:

var SD;
function stopwatch(text) {
    if (SD && text) {
        return;
    }
            ....
}

function f3() {
    clearTimeout(SD);
    SD = false;
    sec = 0;
    min = 0;
    hour = 0;
}

I.e. you can check, if the timeout is already running when the button is clicked and cancel the execution, if needed.

You can test it at updated jsFiddle.

Upvotes: 0

Curtis
Curtis

Reputation: 103418

Don't call stopwatch() directly.

Call something else which checks SDs state, and then calls stopwatch().

<input type="button" name="theButton" id="Start" value="Start"  onClick="startStopWatch();" />

var sec = 0;
var min = 0;
var hour = 0;
var SD;

function startStopWatch(){
    if (!SD){
      stopwatch();   
    }
}

function stopwatch() {
   sec++;
  if (sec == 60) {
   sec = 0;
   min = min + 1; }
  else {
   min = min; }
  if (min == 60) {
   min = 0; 
   hour += 1; }
if (sec<=9) { sec = "0" + sec; }
  document.getElementById("starttime").innerHTML = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
 SD=window.setTimeout(stopwatch, 1000);
}

function f3() {
    if (SD){
       clearTimeout(SD);
    }
}

Live Demo: http://jsfiddle.net/uJPff/2

Upvotes: 2

Related Questions