【定时器案例】:
<button>开始</button>
<button>结束</button>
<button disabled>
<span>已阅读用户协议(5)</button>
</button>
<script>
let go = document.querySelector('button:nth-of-type(1)'),
stop = document.querySelector('button:nth-of-type(2)'),
time = document.querySelector('button:nth-of-type(3)'),
timeId,
i = 5
function startTime() {
clearInterval(timeId)//避免多次点击出现倒计时加速bug
timeId = setInterval(function () {
i--
time.innerHTML = ` <span>已阅读用户协议(${i})</button>`
console.log(i);
if (i === 0) {
i = 5
clearInterval(timeId)
time.disabled = 0
time.innerHTML = ` <span>已阅读用户协议</button>`
}
}, 1000)
}//封装函数
startTime()//设置是否自动倒计时
go.addEventListener('click', function () {
startTime()
})
stop.addEventListener('click', function () {
clearInterval(timeId)
})
</script>