-2

I would like to know how you can create a stopwatch on javascript to start when the button is clicked and then to stop when it reaches 25 clicks and then show the time. Here is my current code:

<script>
var test= 1;

function myFunction(){
   if(test < 26){
      document.getElementById("hello").innerHTML= test;
      test++;
   }
}
</script>

This code counts up to 25 but I want it to count up to 25 with the stopwatch on starting at the first click and finishing on 25 and then showing the time. Thanks

Soren
  • 14,402
  • 4
  • 41
  • 67
johnny
  • 51
  • 4

2 Answers2

1

Pure JS way:

var test = 0;
var start = 0;
var d = 0;

function myFunction(){
    if(test === 0){
        d = new Date();
        start = d.getTime();
    }
    if(test < 25){
        document.getElementById("hello").innerHTML= test;
        test++;
    }
    if(test === 25){
        d = new Date();
        test++;
        document.getElementById("hello").innerHTML= (d.getTime() - start).toString();
    }
}
tfrascaroli
  • 1,178
  • 1
  • 14
  • 26
  • Just a few minor points with this code: (1) `test` starts at 1, so the the if statements gives the wrong results (but easy fixed), and (2) The `test` is only incremented when <25, so click number 26,27,28... also update the time which defeats the purpose of a stop watch... – Soren Sep 23 '14 at 15:04
  • True, I just copy-pasted his lines of code and didn't realize of the 0/1 thing. And yes, I forgot the ending condition of the function. Adding it right now. Tanks for noticing :D – tfrascaroli Sep 23 '14 at 15:09
0

Will reading the time at the the first click and the last click and subtracting the diff now work -- like this;

var test= 1;
var starttime = null;

function myFunction(){
   if (test == 1) starttime = Date.now();
   if(test < 26){
      document.getElementById("hello").innerHTML= test;
   } else {
      alert("Time Taken:" + (Date.now() - starttime));
   }
   test++;
}
Soren
  • 14,402
  • 4
  • 41
  • 67