JavaScript实现简单计时器

Edda ·
更新时间:2024-09-20
· 152 次阅读

本文实例为大家分享了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>



计时器 JavaScript

需要 登录 后方可回复, 如果你还没有账号请 注册新账号