리셋으로 LazyMan 구현

1602 단어
학습 노트, 일상 교류용으로만 사용
function LazyMan(name){
    var queue = [];
    var api = {
        sleep:function(seconds){
            queue.push(function(){
                console.log(`please wait ${seconds} seconds`);
                setTimeout(function(){
                    next();
                },seconds*1000);
            });
            return api;
        },
        eat:function(what){
            queue.push(function(){
                console.log(`Eat ${what}`);
                next();
            });
            return api;
        },
        sleepFirst:function(seconds){
            queue.unshift(function(){
                console.log(`please wait ${seconds} seconds`);
                setTimeout(function(){
                    next();
                },seconds*1000);
            });
            return api;
        },
        hi:function(name){
            queue.push(function(){
                console.log(`hi ${name}`);
                next();
            });
            return api;
        }
    }
    function next(){
        var fn = queue.shift();
        if(fn !== undefined){
            fn.call();
        }
    }
    api.hi(name);
    setTimeout(function(){
        next();
    },0);
    return api;
}
//LazyMan('fengjixuan').sleepFirst(2).eat('banana').eat('apple');
//LazyMan('fengjixuan').sleep(2).eat('banana').eat('apple');
//LazyMan('fengjixuan').eat('banana').eat('apple');
LazyMan('fengjixuan').sleepFirst(2).sleep(10).eat('banana').eat('apple');

좋은 웹페이지 즐겨찾기