美文网首页
用回调实现LazyMan

用回调实现LazyMan

作者: size_of | 来源:发表于2017-09-07 15:53 被阅读0次

    仅作为学习笔记、日常交流使用

    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');
    

    相关文章

      网友评论

          本文标题:用回调实现LazyMan

          本文链接:https://www.haomeiwen.com/subject/tjmijxtx.html