0

Using setInterval to run a function which gives a 'flash' effect to a list.

If I keep the page open, but visit another tab / come back in 10 minutes or so, the setInterval feels like its working every 1 seconds as the function is constantly being called.

Feels to me like its stacking up over time, anyway to fix this?

function flashListItems(){
  $('.imageview_navigation li').each(function(i) {
    $(this).delay((i++) * 100).fadeTo(200, 0.8).fadeTo(200, 1);
  });
}

setInterval(function(){
  flashListItems();
}, 10000);

fiddle: http://jsfiddle.net/6w6wrsm0/

Lovelock
  • 7,689
  • 19
  • 86
  • 186

1 Answers1

1

There's nothing wrong with your code, some web browers slow these types of intervals down to not cause too much usage. So when the webpage is not used, the fastest a interval can go is usually about 1 sec.

There might be a way to fix this, which is mentioned here:

How can I make setInterval also work when a tab is inactive in Chrome?

Just make your animation function tick by real elapsed time.

var div = $('#my-div');
var leftValue = 0;
var interval = (1000/20); //20fps
var before = new Date();

setInterval(function()
{
    now = new Date();
    var elapsedTime = (now.getTime() - before.getTime());

    if(elapsedTime > interval)
    {
        //Recover the motion lost while inactive.
        leftValue += Math.floor(elapsedTime/interval);
    }
    else
    {
        leftValue++;
    }

    div.css("left", leftValue);
    before = new Date();    

}, interval);
Community
  • 1
  • 1
Alex
  • 606
  • 11
  • 23