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>
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值