码迷,mamicode.com
首页 > Web开发 > 详细

js 同步延时调用

时间:2020-02-25 18:09:14      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:detail   break   开始   功能   var   lazy   details   队列   amp   

function LazyMan(name) {
  return new _lazyman(name)
}
function _lazyman(name) {
  this.task = []
  var that = this
  var fn = (function(name) {
    return function() {
      console.log("Hello I'm " + name)
      that.next()
    }
  })(name)
  this.task.push(fn)
  setTimeout(function() {
    that.next()
  }, 0)
  //此处用settimeout执行是因为settimeout会在同步线程都进行完了之后再执行,如果不用settimeout就会同步触发,事件还未都放在队列中,就已经开始执行了
  //关于js同步,异步,事件循环等,可以看这篇文章http://blog.csdn.net/alex8046/article/details/51914205
}
_lazyman.prototype = {
  constructor: _lazyman,
  //next是实现函数在队列中顺序执行功能的函数
  next: function() {
    var fn = this.task.shift()
    fn && fn()
  },

  sleep: function(time) {
    var that = this
    var fn = (function(time) {
      return function() {
        console.log('sleep.......' + time)
        setTimeout(function() {
          that.next()
        }, time)
      }
    })(time)
    this.task.push(fn)
    return this
    //return this是为了实现链式调用
  },

  sleepfirst: function(time) {
    var that = this
    var fn = (function(time) {
      return function() {
        console.log('sleep.......' + time)
        setTimeout(function() {
          that.next()
        }, time)
      }
    })(time)
    this.task.unshift(fn)
    return this
  },

  eat: function(something) {
    var that = this
    var fn = (function(something) {
      return function() {
        console.log('Eat ' + something)
        that.next()
      }
    })(something)
    this.task.push(fn)
    return this
  }
}

LazyMan('Joe')
  .sleepfirst(3000)
  .eat('breakfast')
  .sleep(1000)
  .eat('dinner')

js 同步延时调用

标签:detail   break   开始   功能   var   lazy   details   队列   amp   

原文地址:https://www.cnblogs.com/smzd/p/12362530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!