Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个异步队列Queue,要求按时间依次执行callback #82

Open
Cosen95 opened this issue Apr 2, 2020 · 2 comments
Open
Labels

Comments

@Cosen95
Copy link
Owner

Cosen95 commented Apr 2, 2020

No description provided.

@Cosen95 Cosen95 added the 算法 label Apr 2, 2020
@Cosen95
Copy link
Owner Author

Cosen95 commented Apr 2, 2020

题目如下:

new Queue().task(1000, function () {
    console.log(1);
}).task(2000, function () {
    console.log(2);
}).start()

@Cosen95
Copy link
Owner Author

Cosen95 commented Apr 2, 2020

方案1:

function Queue1() {
    this.queue = []
    this.task = (time, fn) => {
        this.queue.push({fn, time})
        return this
    }
    this.start = () => {
        let deffer = 0
        for (let i of this.queue) {
            deffer += i.time
            setTimeout(i.fn, deffer)
        }
    }
}

方案2:

function Queue2() {
    this.queue = []
    this.task = (time, fn) => {
        this.queue.push(function (resolve) {
            setTimeout(function () {
                resolve(fn())
            }, time)
        })
        return this
    }
    this.start = async () => {
        for (let i of this.queue) {
            await new Promise(i)
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant