MCPcopy Create free account
hub / github.com/course-dasheng/fe-algorithm / limit

Function limit

interview/limit.js:7–44  ·  view source on GitHub ↗
(maxCount)

Source from the content-addressed store, hash-verified

5// }
6
7function limit(maxCount){
8 // [,5]
9 // [2,34,]
10 let queue = []
11 let activeCount = 0
12
13 const next = ()=>{
14 //下一个任务
15 activeCount--
16 if(queue.length>0){
17 queue.shift()()
18 }
19 }
20 const run = async (fn,resolve,args)=>{
21 //执行一个函数
22 activeCount++
23 const result = (async()=>fn(...args))()
24 resolve(result)
25 await result
26 next() //下一个
27 }
28 const push = async (fn,resolve,args)=>{
29 queue.push(run.bind(null,fn,resolve,args))
30 if(activeCount<maxCount && queue.length>0){
31 // 队列没满 并且还有任务 启动任务
32 queue.shift()()
33 }
34 }
35
36 let runner = (fn,...args)=>{
37 return new Promise((resolve)=>{
38 push(fn,resolve,args)
39 })
40 }
41 return runner
42
43
44}
45async function sleep(n,name='test'){
46 return new Promise(resolve=>{
47 console.log(n,name,'start')

Callers 1

startFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected