YogeshChauhan.com

How to create a simple stopwatch using JavaScript?

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.

HTML

Let’s start with simple HTML.

CSS

Let’s make that ugly HTML somewhat pretty.

JavaScript

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.

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

Simple Page Hit Counter in PHPPHPLearn to Make a Simple Contact Us Form using PHP and PDO-MySQLPHPSolution for Xcode 11 Command PhaseScriptExecution failed with a nonzero exit code errorMiscThe fundamental difference between HAVING and WHERE clauses in PostgresPostgresLearn to make a responsive gallery using CSS Grid and without media queriesCSSsubstring() Method in JavaScriptJavaScriptHow To Create a Fullscreen Background Video using CSS and JavaScript?CSSHow to create a flip pricing table using CSS and JavaScript?CSSPre-defined DatePipe format options in Angular 9AngularHow to link/add CSS file to HTML Document?CSSCrypto.getRandomValues() method in JavaScriptJavaScriptHow to animate list items using CSS and JavaScript?CSS