`

对setInterval作简单封装

    博客分类:
  • js
阅读更多
/**
 *  调用方式
 * let i = new Interval(1000)
 * i.do(()=>console.log(new Date()))
 * i.stop()
 */
export default class Interval {
  constructor(duration) {
    this.id = -1
    this.duration = duration
  }

  do(fn) {
    if (this.id > 0) {
      throw Error('just do one thing')
    } else {
      this.id = setInterval(fn, this.duration)
    }
  }
  stop() {
    clearInterval(this.id)
    setTimeout(() => { this.id = -1 }, 100)
  }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics