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

4.实现可以链式调用的延时 #5

Open
conan1992 opened this issue Nov 26, 2019 · 0 comments
Open

4.实现可以链式调用的延时 #5

conan1992 opened this issue Nov 26, 2019 · 0 comments

Comments

@conan1992
Copy link
Owner

Person("Smith").sleepFirst(5).eat("supper");
// 输出:
// 等待5秒
// Wake up after 5
// Hi This is Smith!
// Eat supper

1.分析

1).链接所有 this;

2).把所有任务放到任务队列里面;

3).通过一个方法有序执行队列里面的任务;

2.实现

function person(name){
    return new Person(name);
}
function Person(name){
    this.tasks = [];
    this.tasks.push(()=>{
        console.log('Hi!This is '+name+'.');
        this.then();
    });
    setTimeout(()=>{
        this.then();
    })
}
Person.prototype.eat = function( name ){
    this.tasks.push(()=>{
        console.log('Eat '+name+'.');
        this.then();
    })
    return this;
}
Person.prototype.sleep = function( time ){
    this.tasks.push( ()=>{
        console.log('等待 '+time+'秒.');
        setTimeout(()=>{
            console.log('wake up after '+time+'seconds.');
            this.then();
        },time*1000)
    });
    return this;
}
Person.prototype.sleepFirst = function( time ){
    this.tasks.unshift( ()=>{
        console.log('等待 '+time+'秒.');
        setTimeout(()=>{
            console.log('wake up after '+time+'seconds.');
            this.then();
        },time*1000)
    });
    return this;
}
Person.prototype.then = function(){
    let task = this.tasks.shift();
    task && task();
    return this;
}

3.测试

person("Smith").sleepFirst(5).eat("lunch").sleep(3).eat('cake');

image

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

No branches or pull requests

1 participant