定时器-间歇函数
格式
1 2 3 4
| setInterval(function(){ },△t)
|
代码示例
1 2 3 4 5 6 7 8 9 10
| <div>999</div> <script> const div = document.querySelector("div") let a = 0 setInterval(function (){a++},1000) setInterval(function (){ div.innerHTML = a },1000) setInterval(function (){console.log(a)},1000) </script>
|
运行效果

:warning: 注意
setInterval函数的第一个参数若非匿名函数,只能写函数名,不能加(),加了()相当于调用了该函数,不再会循环执行该函数
关闭定时器
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const div = document.querySelector("div") let a = 0 let a_Id = setInterval(function (){ a++ if(a === 30){ clearInterval(a_Id) clearInterval(b_Id) clearInterval(c_Id) } },1000) let b_Id = setInterval(function (){ div.innerHTML = a },1000) let c_Id = setInterval(function (){ console.log(a) },1000)
|
运行效果
