js 同步延时调用

Posted 霜末之冬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 同步延时调用相关的知识,希望对你有一定的参考价值。

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 同步延时调用的主要内容,如果未能解决你的问题,请参考以下文章

vue同步组件和异步组件的区别

JS中定时器与延时调用

ReleaseMutex:从非同步代码块调用对象同步方法

为啥这段js代码设置断点单步调试能够走通,得到结果;但取消断点直接运行就不行了?

[工作积累] UE4 并行渲染的同步 - Sync between FParallelCommandListSet & FRHICommandListImmediate calls(代码片段

Android:处理同步网络调用