目录
一、定时器
(1)setTimeout(fn,间隔时间)
setTimeout(fn,间隔时间):setTimeout函数,创建定时器,在指定的‘间隔时间(单位是毫秒)’之后调用函数fn,调用一次。
(2)setInterval(fn,间隔时间)
setInterval(fn,间隔时间):setInterval()函数,创建定时器,每间隔time毫秒后调用一次fn函数,循环调用。
(3)clearTimeout(定时器)
clearTimeout(定时器):clearTimeout()函数,取消由setTimeout创建的定时器。
(4)clearInterval(定时器)
clearInterval(定时器):clearInterval()函数,取消由setInterval创建的定时器。
(5)练习
①创建程序距离2022国庆节的倒计时
<!-- 创建程序距离2022国庆节的倒计时 -->
<style>
div{
width: 300px;
height: 100px;
color: black;
margin: 100px auto;
text-align: center;
line-height: 100px;
align-content: center;
border: 1px solid red;
background-color: antiquewhite;
}
</style>
<body>
<div></div>
<script>
function showTime(){
var date1 = new Date('2022-10-01 0:0:0');
var date2 = new Date();
var date = date1-date2;
var d = parseInt(date/(1000*60*60*24));
var h = parseInt((date%(1000*60*60*24))/(1000*60*60));
var f = parseInt((date%(1000*60*60*24))%(1000*60*60)/(1000*60));
var s = parseInt((date%(1000*60*60*24))%(1000*60*60)%(1000*60)/1000);
d = d>=10?d:'0'+d;
h=h>=10?h:'0'+h;
f=f>=10?f:'0'+f;
s=s>=10?s:'0'+s;
var str = '国庆节倒计时:'+d+'天'+h+'时'+f+'分'+s+'秒';
// return str;
document.querySelector('div').innerHTML=str;
setTimeout(showTime, 1000);
}
window.onload = showTime();
// setInterval(function(){
// document.querySelector('div').innerHTML=showTime()
// } ,1000)
</script>
</body>
效果展示:
②页面中包含一个input和一个button,button上有倒计时(倒计时60秒),每间隔一分钟才可以输入一次数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
手机号码:<input type="number">
<button >发送</button>
<script>
// 1、获取页面中的button
let btn = document.querySelector('button');
// 2、设置倒计时,并给按钮注册click事件
let time = 60;
btn.addEventListener('click',function(){//这里可以写匿名函数,也可以在外面定义好后,写函数名
//2.1按钮不可用
btn.disabled=true;
//2.2创建一个定时器,60秒后按钮要可用,60秒内按钮是不可用的并且显示倒计时
let timer = setInterval(function(){
if(time == 0){
btn.disabled=false;//按钮可用
clearInterval(timer)//清除定时器
btn.innerHTML='发送'
}else{
btn.innerHTML='还剩'+time+'秒'
time--//因为一秒调用一次,所以time--指的是每次减一秒
}
},1000)
})
</script>
</body>
</html>
效果展示: