定时任务
window.setTimeout(func,1000)
一秒后执行该func函数,无法传参
需求,需要传参怎么办?
1.定义一个无名函数,在无名函数内部执行
func,可传参
function(){ func(params);}
2.使用闭包
window.setInterval(func,1000)
周期性的执行func,即每一秒执行一次func
案例
<!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>
<style>
#settime{
color:blue;
margin: 0,auto;
font-size: 2em;
text-align:center;
width:200px;
height:100px;
border-radius:30%;
z-index:100;
}
</style>
</head>
<body>
<div style="text-align:center;">
<p style="font-size:1.5em;color:red;">倒计时按钮</p>
<input type="button" id="settime" value="计时器" onclick="settime(this);">
<!--this 触发当前事件的js对象-->
</div>
<script>
var countdown = 60;
function settime(obj){
console.log(countdown);
if (countdown == 0){
obj.setAttribute("value","发送验证码");
obj.removeAttribute("disabled");//恢复可点击
return ;
}else{
obj.setAttribute("disabled",true);//设置不可点击
obj.setAttribute("value","重新发送("+countdown+")");
countdown--;
}
//定时器
setTimeout(function(){
settime(obj);
},1000);
}
</script>
</body>
</html>