<!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" id="phone">
<button>发送</button>
<script>
let btn = document.querySelector('button');
btn.addEventListener('click', function () {
let time = 5;
btn.disabled = true;
let timer = setInterval(function () {
if (time < 0) {
btn.innerHTML = '发送';
btn.disabled = false;
clearInterval(timer);
} else {
btn.innerHTML = time + "秒钟之后重新发送";
time--;
}
}, 1000);
})
</script>
</body>
</html>
不可以将判断是否满足清除定时器的代码写到定时器函数外面,因为js的同步和异步执行,若将其放到定时器函数外面,则其只执行一次。
|