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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How get_template_part helps write reusable code in WordPress?WordPressThe Drupal flowDrupalThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSSanitize inputs using built-in WordPress functionsWordPressWhat happens when we add Numbers and Strings in JavaScript?JavaScriptHow to remove special characters (dash, asterisk etc) from any string in PHP?PHPHow to avoid element shift on border change while hovering in CSS?CSSHow to merge arrays in JavaScript?JavaScriptHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSSPHP Variables ScopePHPReverse a String in JavaScriptJavaScriptHow to add CurrencyPipe in TypeScript file in Angular 9 Project?Angular