原生js计时器和时钟

各种小demo 我后续会上传到,样式内容很少 以js为主,代码如下:

goblinModeL · GitHubgoblinModeL has 2 repositories available. Follow their code on GitHub.icon-default.png?t=N7T8https://github.com/goblinModeL计时器起步延迟一秒可自行修改初始时间为1或者,添加变量 使得首次点击立即执行,下方代码暂时未添加,如有需要可评论 我后续加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>时间和计时器</title>
</head>
<body>
<div style="width: 200px;height: 200px;display: inline-block">
    <h1>时间</h1>
    <h1 class="time"></h1>
    <button onclick="clearInterval(count)">停止</button>
    <button onclick="count=setInterval( ()=>{timer()},1000)">重新</button>
</div>
<div style="width: 400px;height: 200px;display: inline-block;margin-left: 200px">
    <h1>计时器</h1>
    <h1 class="time">00:00:00</h1>
    <button onclick="if (begin===false) {  counts = setInterval(() => {  timer2() }, 1000)}">开始</button>
    <button onclick="suspend=!suspend">暂停</button>
    <button onclick="clears()">清除</button>
</div>
</body>
<script type="text/javascript">
    const date = new Date();
    let H = 0, M = 0;
    S = 0;
    let suspend=false
    let begin=false
let counts
    //简易时间
    const timer = () => {
        const date = new Date();

        const Hours = date.getHours().toString().length > 1 ? date.getHours() : '0' + date.getHours(),
            minutes = date.getMinutes().toString().length > 1 ? date.getMinutes() : '0' + date.getMinutes(),
            Seconds = date.getSeconds().toString().length > 1 ? date.getSeconds() : '0' + date.getSeconds();
        document.getElementsByClassName('time')[0].innerText =
            Hours + ":" + minutes + ":" + Seconds;

    }
    let count = setInterval(() => {
        timer()
    }, 1000)
    //计时器
    const timer2 = () => {
             begin=true;
            suspend == false ? ++S : S;
            S = S.toString().length > 1 ? S : '0' + S;
            M = S == 60 ? (++M , S = 0) : M
            H = M == 60 ? (++H, M = 0) : H
            S = S.toString().length > 1 ? S : '0' + S;
            M = M.toString().length > 1 ? M : '0' + M;
            H = H.toString().length > 1 ? H : '0' + H;
            document.getElementsByClassName('time')[1].innerText =
                H + ":" + M + ":" + S;

    }

const clears=()=>{
     H = 0, M = 0;S = 0;
    clearInterval(counts);
    begin=false;
    document.getElementsByClassName('time')[1].innerText ="00:00:00";

}

</script>
</html>

如有bug 多谢反馈! 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值