1.一个html页面实现,js写在html里面
clock.html
<!DOCTYPE html>
<html>
<head><meta charset="UTF‐8"><title>clock</title><style type="text/css">#clock {color: green;font‐size: 30px;}</style>
</head>
<body>
<script type="text/javascript">let timer;//开始调用function start() {//先清除上一个计时器,再开启一个计时器window.clearInterval(timer);
//1000毫秒调用begin()timer = window.setInterval("begin()", 1000);}//思路:每过1秒钟调用1次时间,并且将时间显示在某个元素内部function begin() {
//得到现在的时间let time = new Date();
//得到h1元素let clock = document.getElementById("clock");
//将时间显示在h1中clock.innerHTML = time.toLocaleString();}//暂停function pause() {
//清除计时器window.clearInterval(timer);}
</script>
<h1 id="clock"> current time </h1>
<input type="button" value="start" onclick="start()"/>
<input type="button" value="pause" onclick="pause()"/>
</body>
</html>
2.html导入外部js文件实现
clock1.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body></body>
<!DOCTYPE html>
<html>
<head><meta charset="UTF‐8"><title>clock</title><style type="text/css">#clock {color: green;font‐size: 30px;}</style><script src="clock1.js"></script>
</head>
<body>
<script>alert("import js file");begin();
</script>
<h1 id="clock"> current time </h1>
<input type="button" value="start" onclick="start()"/>
<input type="button" value="pause" onclick="pause()"/>
</body>
</html>
clock1.js
let timer;function start() {window.clearInterval(timer);timer = window.setInterval("begin()", 1000);
}function begin() {let time = new Date();let clock = document.getElementById("clock");clock.innerHTML = time.toLocaleString();
}function pause() {window.clearInterval(timer);
}