当前位置:主页 > 网页前端 > JavaScript代码 >

js实现时钟定时器

时间:2020-10-05 21:34:33 | 栏目:JavaScript代码 | 点击:

本文实例为大家分享了js实现时钟定时器的具体代码,供大家参考,具体内容如下

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>时钟</title>
 <script type="text/javascript">
 function showClock(){
 // 1. 获取当前时间
 var time = new Date();
 // document.write(time);
 var year = time.getFullYear();
 // document.write(year);
 var month = time.getMonth() + 1;
 // document.write(month);
 
 var day = time.getDate();
 // var day1 = time.getDay();
 // document.write(day1);
 
 var hours = time.getHours();
 // document.write(hours);
 
 var minutes = time.getMinutes();
 // document.write(minutes);
 
 var seconds = time.getSeconds();
 
 
 document.getElementById("clock").innerHTML = year+"-"+month+"-"+day+" "
 +hours+":"+minutes+":"+seconds;
 
 }
 
 var flag = true;
 var id;
 function runClock(){
 var btn = document.getElementById("btn");
 
 if(flag){
  // 计时操作
  id = setInterval("showClock()",1000);
  flag = false;
  btn.innerHTML = "停止";
 }else{
  // 停止计时操作
  clearInterval(id);
  flag = true;
  btn.innerHTML = "动起来";
 }  
 
 }

 
 </script>
 </head>
 <body>
 <button οnclick="showClock()">点击显示时钟</button>
 <div id="clock">
 
 </div>
 <button id="btn" οnclick="runClock()">动起来</button>
 </body>
</html>

您可能感兴趣的文章:

相关文章