一、首先介绍下2者的“含义”及“区别”。
setTimeout(function(){ alert("Hello"); }, 3000); 间隔3秒弹出一次,就不再弹出了
setInterval(function(){ alert("Hello"); }, 3000); 每间隔3秒弹出一次,反复弹出
可以用来写、当前时间、进度条、切换背景、秒钟计时等等
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
#box{
width: 100%;
height: 40px;
position: relative;
background: #ddd;
}
#bar{
width: 10px;
height: 40px;
background: #4CAF50;
position: absolute;
}
</style>
<body>
<input type = "submit" id="stopbtn" value="暂停"><input type = "submit" id="playbtn" value="开始"><input type="text" id="shij">
<div id="box">
<div id="bar"></div>
</div>
</body>
</html>
<script>
//1.秒钟计时器
var c = 0;
var param = 0;
function Shij() {
shij.value = c;
c = c + 1;
param = setTimeout(Shij, 1000);//变量设置全局,后面就可以进行暂停
}
Shij();
stopbtn.onclick = function () {
clearTimeout(param);//清除计时器
}
playbtn.onclick = function () {
Shij();
}
</script>
<script>
//进度条
var i = 0;
function frame() {
if (i == 100) {
clearInterval(timenum);
} else {
i++;
bar.style.width = i + '%';
}
shij.value = i + '%';
}
playbtn.onclick = function (){
i = 0;
timenum = setInterval(frame, 10);
}
stopbtn.onclick = function () {
clearInterval(timenum);
}
</script>