Open zhanhongtao opened 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) } }
思路:让每次函数调用重新开始。