Stopwatch with JavaScript (2) – Start & Stop with Spacebar –


Did you try “Stopwatch with JavaScript”?

Stopwatch with JavaScript Introduction & Demo Today, I share my very first YouTube ...


I got a question about how to start and stop the timer with a spacebar.
I think this is a very useful function, so let’s add it!


Here is the code.

Please add line3~13 right before </script>.


If you want to use “Enter” instead of “Space”, change 32 to 13.


Example (and more)

Key Code
Space 32
Enter 13
S 83


I hope this works well with your stopwatch.
Happy coding 🙂


Working as a freelance programmer in Japan. I try to make coding as simple as possible. Hope you enjoy coding 🙂
  • Andy Tan


    I am running the script on internet explorer 8.0 (ie8) in my office, i can’t get the
    document.onkeydown = function(event) {

    to work.. Was it the ie8 problem?

    Everything else is working, less the spacebar… 🙁

    • Sara

      Hi Andy,
      IE doesn’t pass the event object, so try adding this code.

      document.onkeydown = function(event) {
      event = (event) ? event || window.event; // ←Add !!
      if (event) {

      Hope this helps 🙂

      • Andy Tan

        Thanks. Will give it a try and let you know 🙂
        Happy New Year!