Sunday, November 1, 2009

[jQuery] my setinterval is iterating too much

problem: when i clear my setinterval it takes a few minutes for
everything to stop moving... i think its because i am actually
creating a 'buffer' of setintervals because when i log to console i am
getting more responses than the function seems to be getting called.
not sure what i am missing here... any help would be appreciated.


function animateStarNav(initialize) {
$('.star').each(function(i) {
var pause;
var pause_counter;

if (initialize) {
pause=(Math.floor(Math.random()*1000));
pause_counter++;
if (pause_counter>$('.star').size()) pause=false;
} else {
pause=(Math.floor(Math.random()*5000)+4000);
}

var obj=$(this);
stars[i]=setInterval(function() { positionStar(obj); }, pause);
});
}

// position stars
function positionStar(obj) {

console.log((obj).attr('id'));

if (!docked) {
var new_position=-(Math.floor(Math.random()*200)+300);
var speed=Math.floor(Math.random()*3000)+1000;

(obj).animate({ top:new_position }, speed, 'easeOutElastic');
}
}


// dock star nav
function dockStarNav() {
$('.star').each(function(i) {
clearInterval(stars[i]);
});
docked=true;
}

No comments: