Menu
Coddy logo textTech

Working Stopwatch

Lesson 9 of 10 in Coddy's Stopwatch - HTML/CSS/JS Project course.

Now, once we have the working start and stop buttons, it's time to start counting!

To count, we will use a JavaScript function called setInterval:

const interval = setInterval(func, milliseconds)

The function gets two argument: a function and a number representing milliseconds. The function gets called every number of milliseconds supplied.

So for example:

let count = 0

function updateCount() {
	count += 1;
}

const interval = setInterval(updateCount, 1000)

In the above example, we increase the count variable by 1 every second.

If you want to stop an interval, use clearInterval with the return value of setInterval:

const interval = setInterval(updateCount, 1000)
clearInterval(interval)
challenge icon

Challenge

Medium

Add the following support to your JS file:

  • Once the start/stop button is clicked set an interval that will update the stopwatch text every second by one, make sure it formatted correctly.
  • Once the start/stop button is clicked again clear the running interval.

Once you add a setInterval to your code, you will need to click the reset button on the web view:

Try it yourself

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="styles.css">
</head>
    <body>
        <!-- Write HTML code here -->
        <script src="script.js"></script>
    </body>
</html>

All lessons in Stopwatch - HTML/CSS/JS Project

1Introduction

Overview

4JS Part

Basic Start and StopProject lessonWorking StopwatchProject lessonResetProject lesson