js里显示时间的setInterval和clearInterval的使用

194 阅读1分钟

效果图:

4.png
时间可以动态的改变,点击停止时间,可暂停时间的动态改变。

代码:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>

	</head>

	<body onload="inti()">
		<p>显示当前时间:</p>

		<p id="demo"></p>

		<button onclick="myStopFunction()">停止时间</button>

		<script>
			function inti() {
				document.getElementById("demo").innerText = new Date().toLocaleString();
			}
			var msg = setInterval(function() {
				inti()
			}, 1000);

			function myStopFunction() {
				clearInterval(msg);
			}
		</script>
	</body>

</html>