Yogesh Chauhan's Blog

How to create a simple stopwatch using JavaScript?

in JavaScript on March 30, 2021

I have another post on creating a digital clock. Similar to that example, we’ll use setTimeout method from JavaScript to create the stopwatch.


Let’s start with simple HTML.


Let’s make that ugly HTML somewhat pretty.


Let’s add the variables first.

The variable msec is set as 0 while sec, min and hour variables are set as 1. That’s because we need the microseconds starting from 0 but others will be dependent on microseconds and will be increased by 1. It’ll make more sense once you set it to a zero! You live, you learn!

Also, we need a variable to keep track of the timer, if it’s ON or OFF. That’ why we used timerOn which is OFF(0) initially.

Let’s add the function to start and stop the stopwatch and a function to update the value of microseconds.

That’s working like a charm.

Now, let’s call a function when the microseconds reach at 10 to update the seconds. Similarly, we will create a function to update minutes and hours.

Here’s the code and the demo.

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What are Controlled Components in React?ReactHow to create a full screen loader using CSS and JavaScript?CSSCSS backface-visibility PropertyCSSWhat is a component helper function in React?ReactContent types in DrupalDrupalCheck if mixin is being called in a style rule or not in SCSSSCSSNATURAL JOIN in PostgresPostgresThe basics of CSS Box modelCSSHow different is Handling Events in React vs HTML DOM?ReactHow to create a simple tab interaction using CSS?CSSHow to embed YouTube or other video links in WordPress?WordPressObservation of Human Behavior [Shopping Observation Example]Miscellaneous