2

What's happening

Okay, so I've made a function on my front page where some products are shown besides each other, fading out, changing products and fading back in every 5 seconds. The code looks like this:

var t; $(document).ready(function(){ // Some pre-animation stuff, like loading the products etc. // Initialize animation timer t = setInterval("changeProducts();", 5000); }; function changeProducts() { // Fade out $("#anfBox").fadeTo(200, 0.01, function() { // Change products // Fade back in $("#anfBox").fadeTo(200, 1); }); } 

It all looks fine and runs as it should, except when i go to another window for a minute and then comes back, the changeProducts function is executed rapidly a few times (depending on how long i've been away). The products fade out, change fades in again, and then repeats instantly, where there should be a ~5 second delay.

What I've tried

So what I think I need to do is use something like clearInterval(t) when the focus is lost from the window, then re-initialize the timer when the window is re-entered, i just don't know how to do that, and i'm having a hard time finding anything useful on google.

I'm thinking maybe there's allso a way to run the animations even if the window is not in focus to avoid the function-queue.

I've also tried using setTimeout() instead but with no luck.

Any ideas on how to avoid the animation-queue is much appreciated.

1 Answer 1

4

With the latest browser updates lots of browsers now stop execution of code when current page or tab is not active. When you return that tab/window it executes all of queued actions and you see a rush of effect running each after.

Simply check effect queue before apply another effect, if queue's length is 0 then apply.

Try this (example);

var t; function changeProducts() { // Fade out var $anfBox = $("#anfBox"), queue = $anfBox.queue('fx'); if (queue && queue.length === 0) { $anfBox.fadeTo(200, 0.01, function() { // Change products // Fade back in $anfBox.fadeTo(200, 1); }); } } $(document).ready(function() { // Some pre-animation stuff, like loading the products etc. // Initialize animation timer t = setInterval(changeProducts, 5000); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly, thanks allot. :) The jsfiddle link is a nice touch to the answer as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.