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 onclick="showClock()">点击显示时钟</button>
		<div id="clock">
			
		</div>
		<button id="btn" onclick="runClock()">动起来</button>
	</body>
</html>

 

posted @ 2020-03-25 13:34  JackieDYH  阅读(10)  评论(0编辑  收藏  举报  来源