JS实现简易秒表

 

<!DOCTYPE html>
<html>

<head>
    <title>简易秒表</title>
    <style>
        body {
            text-align: center;
        }
    </style>
</head>

<body>
    <h1>JS实现简易秒表</h1>
    <h3 id="clock">00:00:00</h3>
    <button id="start">开始</button>
    <button id="stop">暂停</button>
    <button id="reset">重置</button>
    <script>
        let n = 0, time = null;
        let clock = document.getElementById('clock');
        let start = document.getElementById('start');
        let stop = document.getElementById('stop');
        let reset = document.getElementById('reset');
        // 开始
        start.onclick = () => {
            clearInterval(time);
            time = setInterval(() => {
                n++;
                clock.textContent = timeStyle(parseInt((n / 3600) % 3600)) + ':' + timeStyle(parseInt((n / 60) % 60)) + ':' + timeStyle(parseInt(n % 60));
            }, 1000 / 60);
        };
        // 暂停
        stop.onclick = () => {
            clearInterval(time);
        }
        // 重置
        reset.onclick = () => {
            n = 0;
            clock.textContent = '00:00:00';
        }
        // 表示样式
        function timeStyle(num) {
            return num < 10 ? ('0' + num) : num;
        }
    </script>
</body>

</html>

 

posted @ 2020-08-17 15:18  JonnyOu1012  阅读(26)  评论(0编辑  收藏  举报