zhanhongtao / blog

Blog for 91885076(QQ群)
http://github.com/zhanhongtao/blog/issues
24 stars 7 forks source link

减少 call stack 深度 #275

Open zhanhongtao opened 7 years ago

zhanhongtao commented 7 years ago

思路:让每次函数调用重新开始。

var Task = function (timeout) {
  this.state = 'stop'
  this.tasks = []
  this.timeout = timeout || 100
}

Task.prototype.add = function (task) {
  if (typeof task === 'function') {
    this.tasks.push(task)
    this.run()
    this.keyframe()
  }
}

Task.prototype.run = function () {
  if (this.state === 'stop') {
    if (this.tasks.length) {
      var task = this.tasks.shift()
      this.state = 'running'
      task(() => {
        this.state = 'stop'
      })
    }
  }
}

Task.prototype.keyframe = function () {
  if (this.timer) clearTimeout(this.timer)
  if (this.tasks.length) {
    this.timer = setTimeout(() => {
      if (this.state === 'stop') {
        this.run()
      }
      this.keyframe()
    }, this.timeout)
  }
}