2-1 setTimeout 超时调用

  1. // 超时调用 间隔一段时间触发,只会触发一次
  2. setTimeout(function(){
  3. console.log("hello world")
  4. },2000)
  5. // 间歇调用 每隔一段时间,就会触发
  6. setInterval(function(){
  7. console.log("1")
  8. },1000)

2-2 setInterval 间歇调用

  1. <button id="btn">停止定时器</button>
  2. <script>
  3. /* 设置定时器的时候,会在window下挂载一个属性 */
  4. /*
  5. clearInterval() 清除定时器
  6. */
  7. var btn =document.getElementById("btn");
  8. var temp =setInterval(function(){
  9. console.log("2")
  10. },1000)
  11. btn.onclick=function(){
  12. clearInterval(temp);
  13. }
  14. </script>