Jquery code for adding/deleting/scrolling list items behaving very strange
This is the piece of code that's in charge of scrolling my vertical list of items.
<script type="text/javascript">
$(document).ready(function(){
var first = 0;
var speed = 700;
var pause = 8000;
function removeFirst(){
first = $('ul#twitter_update_list li:first').html();
$('ul#twitter_update_list li:first')
.animate({opacity: 0}, speed)
.fadeOut('slow', function() {$(this).remove();});
addLast(first);
}
function addLast(first){
last = '<li style="display:none">'+first+'</li>';
$('ul#twitter_update_list').append(last)
$('ul#twitter_update_list li:last')
.animate({opacity: 1}, speed)
.fadeIn('slow')
}
interval = setInterval(removeFirst, pause);
});
</script>
At the first glance, everything seems to work flawlessly. But after about 10 minutes, the list items start to add up (as if they're not getting deleted). After about 15 minutes, there's like 30 of list items (initially, there were only 5).
开发者_如何学JAVAThe content is being inserted in by ajax once, at the document load. I don't think this is relevant so I didn't include that code.
These 2 lines:
.fadeOut('slow', function() {$(this).remove();});
addLast(first);
Run asynchronously. So a new nodes are added faster than the previous first one is removed.
Move addLast()
, like so:
.fadeOut('slow', function() { $(this).remove(); addLast(first); });
and it will work.
See it in action at jsFiddle.
Call setInterval(removeFirst, pause) in the success handler of your ajax call on page load.
精彩评论