1.定时器:有两个参数
setInterval(箭头函数,定时)
setTimeout(箭头函数,定时)
2.关闭定时器
clearInterval():取消通过 setInterval()
创建的定时器。
clearTimeout():取消通过 setTimeout()
创建的定时器。
案例:倒计时10秒结束以后输出'fire'
方法一:setTimeout
setTimeout
for (let i = 0; i <= 10; i++){
setTimeout(()=>{
console.log(i)
},(10 - i)*1000)
}
setTimeout(()=>{
console.log('fire')
},10000)
运行结果:
方法二:setInterval
let count = 10;
let t = setInterval(()=>{
//当count=0时,输出‘fire’,并且关闭定时器
if(count == 0){
console.log('fire')
clearInterval(t)
return
}
console.log(count--)
},1000)
运行结果