js使用定时器实现简单的计时器

实现效果图:
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div1{width: 110px;height: 200px;padding: 50px;background-color: orange;border: 1px solid black;margin: 50px auto 0;}
        #div1 span{font-size: 22px;}
        #div1 button{width: 100px;height: 30px;font-size: 16px;margin-top: 20px;background-color: black;color: orange;}
    </style>
    <script>
        function $(id){
            return document.getElementById(id);
        }
        var i=0;
        var timer=null;
        window.onload=function(){
            $("start").onclick=function(){
                timer=setInterval(function(){
                i++;
                $("sec").innerHTML=double(i%60);
                $("min").innerHTML=double(parseInt(i/60)%60);
                $("hour").innerHTML=double(parseInt(i/3600));
            },1000);
            }
            $("pause").onclick=function(){
                clearInterval(timer);
            }
            $("reset").onclick=function(){
            clearInterval(timer);
            i=0;
            $("sec").innerHTML="00";
            $("min").innerHTML="00";
            $("hour").innerHTML="00";
            }
          }
         
        function double(n){
            if(n<10){
                return "0"+n;
            }else{
                return n;
            }
        }
    </script>
</head>
<body>
    <div id="div1">
        <span id="hour">00</span>
        <span>:</span>
        <span id="min">00</span>
        <span>:</span>
        <span id="sec">00</span>
        <br>
        <button id="start">开始</button>
        <button id="pause">暂停</button>
        <button id="reset">复位</button>
    </div>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值