第一种:
<body>
<button id="btn">3</button>
<script>
var num =3;
var btn = document.getElementById("btn");
var timer = setInterval(function(){
num--; //-1
console.log(num)
if(num>=0){
btn.innerHTML = num;
}else{
clearTimeout(timer)
}
},1000)
</script>
</body>
第二种:
<body>
<button id="btn">3</button>
<script>
/* 递归:函数调用函数自身 */
var btn = document.getElementById("btn");
var num = 3;
function go() {
setTimeout(function () {
num--; //
if (num >= 0) {
btn.innerHTML = num;
go();
}
}, 1000)
}
go();
</script>
</body>
五秒倒计时小练习:
<body>
<button id="btn">发送验证码</button>
<script>
var num =5;
var btn = document.getElementById("btn");
var timer
/* 1、让按钮进入倒计时的状态(不能点击的状态)*/
btn.onclick = function(){
this.disabled = true;
this.innerHTML = num;
/* 2、每过1s num-- */
timer = setInterval(function(){
num--
if(num>=0){
btn.innerHTML = num;
}else{
btn.disabled = false;
btn.innerHTML = "发送验证码";
num =5;
clearInterval(timer);
}
},1000)
}
/* 使用setTimeout去实现 */
</script>
</body>