定时器

211 阅读1分钟

window对象上提供的两个方法

  • window.setTimeout()
  • window.setInterval()

setTimeout() 间隔时间内 只执行一次

  • setTimeout(函数, 间隔时间(单位:毫秒))
   // setTimeout(function() {
   //   alert('hello world!')
   // }, 3000)

   function fe() {
     console.log('fefe')
   }
  • 浏览器会为每个定时器 分配一个id 用来标识这个定时器
    var timer1 = setTimeout(fe, 3000)
    console.log(timer1)

    var timer2 = setTimeout(fe, 3000)
    console.log(timer2)
  • 一般都会把用完的定时器 清除掉
  • 清除定时器
  • window.clearTimeout(定时器id)
    var arr = [10, 20, 30, 40]

    function fn(item, ind) {
       console.log(item, ind)
    }

     arr.forEach(fn)
  • setInterval() 每间隔一段时间 就执行一次
    • setInterval(函数, 间隔时间(单位:毫秒))
    var timer3 = setInterval(function() {
      console.log('hello')
    }, 1000)

清除定时器

     window.clearInterval(timer3)