如何排队功能?

时间:2014-03-14 12:06:19

标签: javascript jquery

我的代码中有多个函数,但我想先运行我想要的函数.....

通过我的编码方式,func1()在所有函数func2,func3,func4之后运行。

func1();//run it first forcefully with js
func2();//this should run at same time of func1
func3();//this should run after the func1, and func2
func4();//this should run after the func1, and func2

我使用jquery尝试使用queue()方法func1().queue();,但似乎错了,因为我们无法将函数从doc

排队

那么,有什么技术吗?

2 个答案:

答案 0 :(得分:1)

Javascript是单线程的。只有一个功能可以访问页面。您可以使用web-workers执行某些操作。但是那些无法访问DOM的人。它们还需要一个现代的HTML5浏览器。

对于一个接一个地运行函数,可能最容易在函数2的末尾调用函数3。

答案 1 :(得分:0)

Boelensman1是对的。 Jorg为Promisses提供了建议。

但假设你的所有功能都是异步的,并且承诺不可用...... func1和func2应该在完成时运行回调。

function mockQueue(fn1, fn2, readyCallback) {
  // It's running immediately
  fn1(decFnCount); // run it first forcefully with js
  fn2(decFnCount); // this should run at same time of func1

  var fnCount = 2;
  function decFnCount() {
    if (!fnCount--) readyCallback();
  }
}

mockQueue(func1, func2, function() {
  // It's waiting func1 and func2
  func3(); //this should run after the func1, and func2
  func4(); //this should run after the func1, and func2
})