我正试图通过jQuery +JavaScript来实现这一点:
我有需要按顺序调用的命令/函数,它们之间有一个小的延迟。这些例子包括更改元素的css属性,显示隐藏另一个元素等等。
据我所知,JavaScript没有睡眠功能。所以我想知道jQuery是否有支持这个特性的插件?
从本质上说,像$(window).schedule(function() { /* do something here*/ }, 500);
这样的函数是很好的。这将将函数推入队列,并在执行队列中的所有先前函数时立即执行,如果队列中没有函数,则将立即执行。整数参数指定此函数与其前面函数之间的延迟。
我想我知道如何从地面建立这个,但我希望有一个插件,因为它将挽救我的车轮再发明。
如果没有..。我会建造这个并释放它。:)
发布于 2014-08-31 05:16:01
我不知道已经存在一个特定的插件(但如果没有插件的话,我会感到惊讶)。但是,如果您只想要一个不与任何特定元素相关联的通用队列,那么没有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/
发布于 2014-08-31 07:52:14
使用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()
调用。
https://stackoverflow.com/questions/25588978
复制相似问题