样式一:自动倒计时
<body>
<div class="box"></div>
</body>
<script>
let box = document.querySelector('.box')
let id = 1
let count = 5
box.innerHTML = count
function time() {
if (id) {
clearInterval(id)
}
id = setInterval(() => {
if (count <= 0) {
clearInterval(id)
return
}
count--
box.innerHTML = count
}, 1000)
}
time()
</script>
样式2:点击倒计时,到点并禁止点击
<body>
<div class="time"></div>
<button class="btn">点击倒计时</button>
</body>
<script>
let times = document.querySelector('.time')
let btn = document.querySelector('.btn')
let id = 1
let count = 10
times.innerHTML = count
btn.addEventListener('click', function () {
function time() {
if (id) {
clearInterval(id)
}
id = setInterval(() => {
if (count <= 0) {
clearInterval(id)
btn.setAttribute('disabled', 'disabled')
return
}
count--
times.innerHTML = count
}, 1000)
}
time()
})
</script>