zoukankan      html  css  js  c++  java
  • 实现LazyManInit('Tony').eat('rice').sleep(1000).sleepFirst(2000)

    代码是参考别人的,我就加点我写的时候不理解的地方吧。

    function LazyMan(name) {
      this.taskList = [];
      console.log(`I am ${name}`);
       setTimeout(() => {
        this.next();
      }, 0)  //setTimeout是异步任务,js会先执行同步任务,这里的同步任务就是把要执行的所有任务推入一个数组。
    }
    
    
    LazyMan.prototype.next = function () {
      if (this.taskList.length > 0) {
        this.taskList.shift()(); //从数组的第一个任务开始执行。
      }
    }
    
    LazyMan.prototype.eat = function (food) {
      this.taskList.push(() => {
        console.log(`I am eating ${food}`);
        this.next();  //每个任务执行完弹出下一个任务,这样当前的js执行栈只有这一个任务,就不会出现任务执行顺序错乱。
      })
      return this;
    }
    
    LazyMan.prototype.sleep = function (time) {
      this.taskList.push(() => {
        setTimeout(() => {
          console.log(`等待 ${time / 1000} 秒`)
          this.next();
        }, time);
      })
      return this;
    }
    
    LazyMan.prototype.sleepFirst = function (time) {
      this.taskList.unshift(() => {
        setTimeout(() => {
          console.log(`先等待 ${time / 1000} 秒`)
          this.next();
        }, time)
      }) //将sleepFirst推入第一个任务,让它不管在什么位置都第二个执行
      return this;
    }
    
    function LazyManInit(name) {
      return new LazyMan(name)
    }
    
    LazyManInit('Tony').eat('rice').sleep(1000).sleepFirst(2000);
  • 相关阅读:
    WordPress使用记录
    Sql Server数据库的存储过程
    (一)vs2010 新建、使用dll
    Commons Betwixt : Turning beans into XML
    error: failed to attach to process ID 0
    java中常用的内存区域
    计算N阶乘中结尾有多少零
    计算出两个日期相隔多少天
    Cognos Active Report 时间区间选择的解决办法
    PHP heredoc 用法
  • 原文地址:https://www.cnblogs.com/userGao/p/14148439.html
Copyright © 2011-2022 走看看