2014-08-31 67 views
3

我试图用jQuery + JavaScript来实现这一目标:jQuery函数调度功能

我有命令/功能需要在一个序列被调用,在他们之间有一个小的延迟。这些示例包括更改元素的css属性,隐藏另一个元素等。

据我所知,JavaScript没有睡眠功能。所以我想知道如果jQuery有一个插件或支持此功能的东西?

本质上,像$(window).schedule(function() { /* do something here*/ }, 500);这样的功能会很好。这将把函数推入队列中,并在队列中所有先前的函数执行后立即执行,如果队列中没有函数,则会立即执行。整型参数指定此函数与其之前的函数之间的延迟。

我想我知道如何从头开始建立这个,但我希望有一个插件,因为它可以帮助我避免重新发明轮子。

如果没有..我会建立这个并释放它。 :)

+0

它取决于您的函数,同步或异步... – dashtinejad 2014-08-31 04:37:26

+0

函数应该一个接一个地执行(同步),但是,它们正在执行的“线程”应该是异步的。本质上,这将模拟一个多线程环境,在这个环境中,页面被正常加载/使用,但有一个“后台线程”依次运行这些功能。 – l3utterfly 2014-08-31 04:40:06

+2

应该可以通过内置函数setTimeout和setInterval来实现,或者我错过了什么?您可以使用一些外部状态,如排序队列,以确保事件按顺序完成(尽管它们仍然是异步的并且不会按照您的要求阻止)。 – Shashank 2014-08-31 05:02:28

回答

3

我不知道一个特定的插件已经存在(虽然我会很惊讶,如果没有一个)。但是,如果你只是想不与任何特定的元素相关联的一般队列,这很容易做到不jQuery的,或许是这样的:

function Scheduler() { 
    var queue = [], 
     timer, 
     next = function() { 
      var item = queue.shift(); 
      if (item) { 
       timer = setTimeout(function() { 
        item.cb.call(item.thisObj); 
        timer = null; 
        next(); 
       }, item.delay); 
      } 
     }; 
    this.schedule = function (delay, cb, thisObj) { 
     queue.push({ 
      cb: cb, 
      delay: delay, 
      thisObj: thisObj 
     }); 
     if (!timer) next(); 
     return this; 
    }; 
} 

var scheduler = new Scheduler(); 
scheduler.schedule(2000, function() { 
    $("h1").css("color", "red"); 
}); 
scheduler.schedule(500, someFunc) 
     .schedule(3000, someOtherFunc) 
     .schedule(1500, anotherFunc); 

主要.schedule()方法返回调度的实例,所以如图所示,您可以链接重复呼叫。你可以(可选)通过回调函数的上下文为显示在下面的演示:http://jsfiddle.net/euggc0r2/1/

0

使用jQuery的内置queue()dequeue()delay()方法,像这样:

$(function() { 
    $('#yourElement') 
     .queue('myQueue', function() { 
      /* do stuff... */ 
      // ...then tell jQuery to run the next method 
      // in the 'myQueue' queue in 2 seconds. 
      $(this).delay(2000, 'myQueue').dequeue('myQueue'); 
     }) 
     .queue('myQueue', function() { 
      /* do different stuff... */ 
      // ...then tell jQuery to run the next method 
      // in the 'myQueue' queue in 2 seconds. 
      $(this).delay(2000, 'myQueue').dequeue('myQueue'); 
     }) 
     ... 
     ... 
     ... 
     .dequeue('myQueue'); // run the first function in the queue. 
})(); 

通常你会排队所有功能,然后在完成时调用初始的dequeue()