一:时钟
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <meta http-equiv="X-UA-Compatible" content="ie=edge">
7 <title>时钟</title>
8 </head>
9 <body onload="startTime()">
10 <script>
11 function startTime(){
12 var d = new Date();
13 var h = d.getHours();
14 var m = d.getMinutes();
15 var s = d.getSeconds();
16 m = checkTime(m);
17 s = checkTime(s);
18
19 document.getElementById("time").innerHTML = h + ":" + m + ":" + s + " ";
20 setTimeout(startTime,1000);
21 }
22 //分 秒显示个位数加0
23 function checkTime(i){
24 if(i < 10) {
25 i = "0" + i;
26 }
27 return i;
28 }
29 </script>
30
31 <div id="time"></div>
32 </body>
33 </html>
计时器
方法:
setInterval
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>计时器</title>
</head>
<body>
<div id="timeClock"></div>
<button id="stop" onclick="stopTime()">停止计时</button>
<script>
//setInterval() 间隔指定的毫秒数不停地执行指定的代码
//clearInterval() 停止setInterval方法执行的代码
//指定刷新页面
var mytime = setInterval(function () {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("timeClock").innerHTML = t;
}, 1000);
function stopTime(){
clearInterval(mytime);
}
</script>
</body>
</html>
setTimeout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>setTimeout</title>
</head>
<body onload="myTime()">
<button id="stopAlert" onclick="stopAlert()">停止对话框弹出</button>
<script>
//间隔三秒弹出对话框hello 采用回调该函数方法 点击按钮清除
var t;
function myTime() {
alert("hello");
t = setTimeout(function () {
myTime();
}, 3000);
}
function stopAlert() {
clearTimeout(t);
}
</script>
</body>
</html>
区别:setInterval 自己执行 setTimeout 延时执行