Looping queue with jQuery
I've got some very simple code below that I want to use as a starting point for a bigger jQuery solution. I need for the count() function to loop, but am not able to achieve this with the code below which only runs once and then stops. Would appreciate some pointers.
$(function() {
count();
});
function count(){
var $count = p开发者_如何学PythonarseInt($("#count").text());
$("#count").text($count).delay(2000).queue(function() {
$(this).text($count+1);
count();
});
}
You need to call the next function in the queue, like this:
$(count);
function count(){
var $count = parseInt($("#count").text());
$("#count").text($count).delay(2000).queue(function(n) {
$(this).text($count+1);
count();
n();
});
}
You can test it out here. Alternatively, you could replace n()
with $(this).dequeue()
, either way works. If it helps, you could also slim it down a bit, like this:
$(count);
function count(){
$("#count").delay(2000).queue(function(n) {
count();
$(this).text(function(i, t) { return parseInt(t, 10)+1; }).dequeue();
});
}
You can test that version here.
精彩评论