user1926053
user1926053

Reputation: 7

setInterval JavaScript not working

I'm working on a project where I use setInterval. I have read up on it a little bit, but I can't really understand it. What happens is it works fine, but after around 20 seconds it starts to get faster and faster until it lags out my pc.

var autorefresh = setInterval(function () {
    $('#holder').fadeOut('slow').load('index.php').fadeIn('slow');
}, 5000);

As I said this works fine, until it starts getting gradually faster and faster.

Upvotes: -1

Views: 146

Answers (1)

Joe
Joe

Reputation: 47609

I don't know what you're trying to do, but what this code will do is increase the number of concurrently running functions until, as you say, it becomes unmanageable. If a request takes more than 5 seconds (which is possible if you have many pages fetching creating high load) then you will have more than one load in progress at any time.

EDIT: The asker would like to "refresh a div every 5 seconds".

The reason this isn't working is because refreshing is not instantaneous, it takes time. But the loop does not respect that and refreshes ever 5 seconds no matter how long the load takes. This means that at any point the network may respond with one of the ajax requests and fadeIn, and you may get two fadeIns running at once.

To fix this, we wait until the ajax load and the fadeIn has completed before setting a timeOut for another request.

var refresh = function() {
    $('#holder').fadeOut('slow').load('index.php').fadeIn("slow",
        function(){setTimeout(refresh,5000)});
}
refresh();

Upvotes: 7

Related Questions