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 align='center'>0 </div> <br> <br> <div class='butDiv'>    <button type='button' id='start'>開始</button> <button type='button' id='stop'>停止</button> <button type='button' id='reset'>復位</button>  </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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: