jQuery函数调度功能



我正试图用jQuery+JavaScript:来实现这一点

我有一些命令/函数需要按顺序调用,它们之间有一个小延迟。这些例子包括更改一个元素的css属性、显示隐藏另一个元素等。

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

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

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

如果没有。。我将构建并发布它。:)

我不知道已经存在一个特定的插件(尽管如果没有,我会感到惊讶)。但是,如果您只想要一个不与任何特定元素关联的通用队列,那么在没有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/

使用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()调用。

最新更新