By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Stopwatch Creation HTML with DOM and JavaScript

+3 votes

Write a JS program that implements a web timer that supports minutes and seconds. The user should be able to control it with buttons. Clicking [Start] resets the timer back to zero. Only one of the buttons should be enabled at a time (you cannot stop the timer if it’s not running).

There will be no input/output, your program should instead modify the DOM of the given HTML document.

Sample HTML:

<div id="time" style="border:3px solid blue; text-align:center; font-size:2em; margin-bottom:10px">00:00</div>
<button id="startBtn">Start</button>
<button id="stopBtn" disabled="true">Stop</button>
<script>window.onload = function() { stopwatch(); }</script>


create stopwatch with javascript

asked in JavaScript category by user sam

2 Answers

+2 votes

My solution with HTML and JavaScript inside it:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
<div id="time" style="border: 3px solid blue; text-align: center;font-size: 2em; margin-bottom: 10px">00:00</div>
<button id="startBtn">Start the clock</button>
<button id="stopBtn" disabled="true">Stop the clock</button>

    window.onload = function () {

    function stopWatch() {
        let time, intervalId;
        let startBtn = document.getElementById("startBtn");
        let stopBtn = document.getElementById("stopBtn");

        startBtn.addEventListener("click", function () {
            time = -1;
            intervalId = setInterval(incrementTime, 1000);
            startBtn.disabled = true;
            stopBtn.disabled = false;

        stopBtn.addEventListener("click", function () {
            startBtn.disabled = false;
            stopBtn.disabled = true;

        function incrementTime() {
            document.getElementById("time").textContent =
                    ("0" + Math.trunc(time / 60)).slice(-2) +
                    ":" + ("0" + (time % 60)).slice(-2);


answered by user samfred5830
+1 vote