1

Hi I'm working on a reaction test that checks how fast it takes for the user before they react, and I can't really find what I'm looking for. I was just wondering how to make a simple stopwatch in seconds and milliseconds so I can call the function later in HTML onclick.

Here is my code so far:

HTML

<input type="button" class="first" value="Call" onclick="call function" />

and that's pretty much it... I know HTML, CSS, JavaScript and a little bit jQuery.

Thanks in advance !

Nikki
  • 301
  • 1
  • 2
  • 18
  • use `setInterval()` when the event is started, and stop it when the button is clicked. – Callum Linington Jan 08 '15 at 09:30
  • There is a stopwatch implemented in javascript here http://stackoverflow.com/questions/20318822/how-to-create-a-stopwatch-using-javascript and it has a nice demo – Gerard Sexton Jan 08 '15 at 09:35
  • @Gerard Sexton yeah it's nice I've seen it before but I don't really know how to call the start and stop function in HTML – Nikki Jan 08 '15 at 09:41

1 Answers1

4

As a basic starting point you want to use setInterval to increment the stopwatch, with an additional function to toggle/reset it.

You can then either bind the click handler directly to the button (per below), or - I would tend to recommend you bind it in the Javascript itself (e.g. with .onclick=function(){....})

var s = 0,
  ms = 0,
  sEl = document.getElementById('s'),
  msEl = document.getElementById('ms'),
  play = false;
stopwatch = setInterval(function() {
  if (!play) return;
  if (ms === 99) {
    s += 1;
    ms = 0;
  } else {
    ms += 1;
  }
  update();

}, 1);

function update() {

  sEl.innerText = s;
  msEl.innerText = ms;
}

function toggle() {
  if (!play) {
    s = 0, ms = 0;
    update();
  }
  play = !play;
}
body {
  font-family: arial;
}
#s {
  font-size: 50px;
}
#ms {
  font-size: 30px;
  display:inline-block;
  width:35px;
}
button {
  border: 1px solid grey;
  background: lightgrey;
  padding: 10px 40px;
}
<span id="s">0</span>s <span id="ms">00</span>ms
<br />
<button onclick="toggle();">Toggle</button>
SW4
  • 69,876
  • 20
  • 132
  • 137