一道题目,实现延时队列,结构是 value 和 time,time 表示延时时间,队列里数据顺序执行(避免并发),有知道 eventloop 每次 tick 会取出一个 promise 的特性可以实现,还有其他什么办法么?
注意:纯 JS
1
Zenyk 2020-02-05 11:13:39 +08:00
generate、requestanimationframe
|
2
lovedebug 2020-02-05 11:18:58 +08:00
生成器 + promise 可以实现
|
3
rabbbit 2020-02-05 11:34:22 +08:00
function sleep(time) {
return new Promise(resolve => { setTimeout(() => { resolve(); }, time); }); } async function queue(jobs, func) { console.log(jobs); for (let i of jobs) { await sleep(i.time) func(i.value) } } const jobs = [ { value: 1, time: 1000 }, { value: 2, time: 1000 }, { value: 3, time: 1000 }, { value: 4, time: 1000 }, { value: 5, time: 1000 } ]; queue(jobs, (value)=> console.log(value)); |
4
f0rger 2020-02-05 11:36:49 +08:00 via iPhone
Promise,Array.reduce
|
5
rabbbit 2020-02-05 11:40:14 +08:00
function sleep(time) {
return new Promise(resolve => { setTimeout(() => { resolve(); }, time); }); } async function* queue(jobs) { for (let i of jobs) { await sleep(i.time) yield i.value } } const jobs = [ { value: 1, time: 1000 }, { value: 2, time: 1000 }, { value: 3, time: 1000 }, { value: 4, time: 1000 }, { value: 5, time: 1000 } ]; (async function(){ for await (let i of queue(jobs)) { console.log(i); } })(); |