-
Notifications
You must be signed in to change notification settings - Fork 20
Open
Description
概述
我们都可以使用动画来使我们的页面有趣生动。
很多动画第三方库都提供了动画队列功能,帮助我们缓冲我们的动画,使它们按照顺序和特定的间隔执行。
原理
其实原理并不是很难,借助JavaScript的高阶函数特性可以实现。
我们只需要把更新动画的操作封装到(箭头)函数里,然后借助异步事件队列,不停地去查询队列里是否还有需要执行的动画回调,如果还有的话,在特定间隔后放到异步事件队列里,等待被执行,执行完了之后会继续查询队列,直到队列为空,然后更新状态。
实现
const QueueState = {
running: 1,
stopping: 0
}
const actQueue = {
queue: [],
interval: 300,
status: QueueState.stopping,
run: function () {
let shuoldGoOn = () => {
if (this.queue.length !== 0) {
this.queue.shift().call(null)
return true
} else {
this.status = QueueState.stopping
return false
}
}
let step = () => {
setTimeout(() => {
if(shuoldGoOn()) step()
}, this.interval)
}
step()
},
push: function (cb) {
this.queue.push(cb)
if (this.status === QueueState.stopping) {
this.status = QueueState.running
setTimeout(() => {
this.run()
})
}
}
}
对外仅暴露了API:
actQueue.push(),插入执行动画回调actQueue.interval,设置队列执行间隔
Metadata
Metadata
Assignees
Labels
No labels