Created
December 23, 2018 09:45
-
-
Save jation/02e84b5585f95f864c2531e5327384d2 to your computer and use it in GitHub Desktop.
a delay queue....
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Task { | |
constructor(task, taskParam, delay) { | |
this.task = task; // 传入一个需要被执行的函数 | |
this.taskParam = taskParam; // task的参数,一个或多个参数装载数组里!数组里!数组里! | |
this.delay = delay || 0; | |
} | |
action() { | |
// ... | |
typeof this.task === 'function' && this.task.apply(null, this.taskParam); | |
} | |
} | |
class DelayQueue{ | |
constructor(options) { | |
this.minTaskDelay = options.minTaskDelay || 1000; // 每个任务最小执行时间 | |
this.tasks = []; | |
this.paused = true; | |
this.tasksFinishedCallback = options.tasksFinishedCallback; | |
this.pausedCallback = options.tasksFinishedCallback; // 这个没实现,需要就自己实现一下 | |
} | |
//相当于inqueue | |
addTask(task){ | |
// ... | |
this.tasks.push(task); | |
} | |
batchAddTask(arrTasks){ | |
this.tasks = this.tasks.concat(arrTasks); | |
} | |
//出队 | |
dequeue(){ | |
const _this = this; | |
if(this.paused || _this.tasks.length === 0) return; | |
let singleTask = this.tasks.shift(); | |
singleTask.action(); | |
if(this.tasks.length === 0){ | |
typeof this.tasksFinishedCallback === 'function' | |
&& this.tasksFinishedCallback(); | |
this.paused = true; | |
} | |
setTimeout(_this.dequeue.bind(this), Math.max(singleTask.delay, _this.minTaskDelay)); | |
} | |
//启动,或者继续 | |
run(){ | |
this.paused = false; | |
this.dequeue(); | |
} | |
//暂停 | |
paused(){ | |
// ... | |
this.paused = true; | |
} | |
//清除队列 | |
clearQueue(){ | |
this.paused(); | |
this.tasks = []; | |
} | |
} | |
// 调用示例 | |
// 调用示例 | |
// 调用示例 | |
// 调用示例 | |
// 调用示例 | |
//要被执行的任务 | |
function broadcast(content){ | |
console.log("叫号拉!" + content); | |
} | |
let dq = new DelayQueue({ | |
minTaskDelay: 1000, | |
tasksFinishedCallback() { | |
console.warn('所有任务完成了!'); | |
} | |
}) | |
let task1 = new Task( | |
broadcast, | |
["林仙茂请到1234号诊室就诊"], | |
2000,//预计2000ms才能播放完 | |
) | |
let task2 = new Task( | |
broadcast, | |
["第二次!林仙茂请到1231231234号诊室就诊"], | |
3000,//预计3000ms才能播放完 | |
) | |
let task3 = new Task( | |
broadcast, | |
["第3333次!林仙茂请到1231231234号诊室就诊"], | |
1000,// | |
) | |
let task4 = new Task( | |
broadcast, | |
["第4444444次!林仙茂请到1231231234号诊室就诊"], | |
500,// | |
) | |
dq.batchAddTask([task1, task2, task3, task4]); | |
dq.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment