SOURCE


class Queue {
    constructor(props) {
        this.init(props)
    }
    init(props) {
        const { arr = [], func, limit = 6 } = props || {}
        if (!arr.length || !func) return
        this.count = 0
        this.isCancel = false
        this.arr = [...arr]
        this.limit = Math.min(limit, arr.length)
        this.func = func
        this.loop()
    }
    async loop() {
        if (this.isCancel || !this.arr.length) return
        this.count += 1
        if (this.count < this.limit) {
            this.loop()
        }
        await this.func(this.arr.shift())
        if (this.count >= this.limit) {
            this.loop()
        }
        this.count -= 1
    }
    cancel() {
        this.isCancel = true
    }

}

function promiseFunc(props) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('')
            // console.count('count')
            console.log(props, 'props')
        }, Math.random() * 1000 + 1000)
    })
}

const arr = Array(10).fill('').map((v, i) => i)
console.time('test')
const queue = new Queue({ arr, func: promiseFunc })
setTimeout(() => {
    queue.cancel()
    queue.init({ arr, func: promiseFunc })
}, 1000 * 1)

console 命令行工具 X clear

                    
>
console