JavaScript实现简单计时器

本文实例为大家分享了JavaScript实现简单计时器的具体代码,供大家参考,具体内容如下

JavaScript实现简单计时器

<!DOCTYPE html>
<html lang=\"en\">
<head>
    <meta charset=\"UTF-8\">
    <title>计时器</title>
    <style>
        .bigDiv {
            margin: 50px auto;
            width: 200px;
            height: 200px;
            background-color: lightskyblue;
            border-radius: 10px;
        }

        #showNum {
            width: 200px;
            height: 20px;
            background-color: orange;
            text-align-all: center;

            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class=\"bigDiv\">
    <h2 align=\"center\">计时器</h2>
    <div id=\"showNum\" align=\"center\">
        0
    </div>
    <br>
    <br>
    <div class=\"butDiv\">&nbsp&nbsp&nbsp&nbsp
        <button type=\"button\" id=\"start\">开始</button>
        &nbsp
        <button type=\"button\" id=\"stop\">停止</button>
        &nbsp
        <button type=\"button\" id=\"reset\">复位</button>
        &nbsp
    </div>
</div>
<script>
    //定义显示的时间
    let int = null;
    /**
     * 开始  单击事件
     */
    document.getElementById(\"start\").addEventListener(\'click\', function () {
        if (int == null) {
            //设置定时器
            //每隔参数二毫秒执行一次参数一
            int = setInterval(startNum, 1000);
        }
    });
    /**
     * 停止   单击事件
     */
    document.getElementById(\"stop\").addEventListener(\'click\', function () {
        //清除定时器,
        clearInterval(int);
        int = null;
    });
    /**
     * 复位    单击事件
     */
    let num = 0;
    document.getElementById(\"reset\").addEventListener(\'click\', function () {
        if (int == null) {
            num = 0;
            //将时间变成0
            document.getElementById(\"showNum\").innerHTML = num;
        }
    });

    function startNum() {
        num++;
        //持续改变时间
        document.getElementById(\"showNum\").innerHTML = num;
    }
</script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容