settingsAccountsettings
Menusettings

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).

Input/Output:
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>

Examples:

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">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<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>

<script>
    window.onload = function () {
        stopWatch();
    }
</script>

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

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

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

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

 

answered by user samfred5830
+1 vote
...