开发者

Help with JS setInterval, it goes crazy sometimes!

Hey guys. I have having a bit of trouble with this script I wrote regarding setInterval. It sometimes just goes crazy and starts firing repeatly even before the interval time has hit.

Basically I have this slider and I want it to slide automatically at intervals and this is the script I have but like I said it goes crazy have a little bit. What am I doing wrong?

var current = 1;
function autoAdvance()
{
    if(current === -1) { return false; }

    jQuery('#slide_menu ul li a').eq(cur开发者_开发技巧rent%jQuery('#slide_menu ul li a').length).trigger('click',[true]); 
    current++;
}
var itvl = setInterval(function(){autoAdvance();},8000);


setInterval (as with setTimeout) adds the callback function onto the event queue when the timeout expires - if there is other event handling happening at the same time, this can lead to multiple queued callbacks. I prefer to use setTimeout and have the callback function schedule another timeout. This way you will only schedule the next call once the previous one has completed.

function callback(){
    setTimeout(callback,8000);
}
setTimeout(callback,8000);

Oh, also, there is no need to wrap autoAdvance in a function in your setInterval.

setTimeout(autoAdvance,8000);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜