YogeshChauhan . com

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.

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.

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What is Hadoop and Hadoop Ecosystem?MiscHow to detect the Blog Page in WordPress?WordPressUPDATE and DELETE Statements in PostgresPostgresHow to show confirmation alerts with OK and cancel buttons using Swift 5?SwiftGlobal JavaScript methods to convert variables to numbersJavaScriptHow to apply style only to first child and/or only to children other than the first child?CSSHow to get the height and width of an element using JavaScript?JavaScriptLEFT JOIN in PostgresPostgresWhat are Null Sessions?MiscHow to add navigation menu in Angular 9 app?AngularPHP arrays for US states’ full names and abbreviationsPHPForcing the domain to serve securely using HTTPSMisc