4

So i'm trying to create a small personal use jQuery plugin. I have the function completed but the setInterval() function fires twice for some reason and I can't seem to figure out why. At first it seems like it doesn't fire twice but I know by testing (adding an alert on each trigger of the interval) that it fires twice, on the example here you can see that it gradually gets faster and faster (after about 2 minutes it'll be really fast) this is the result of it firing twice.

Can someone please help me how to fix this?

The Javascript code:

(function( $ ) {

  $.fn.imageSwap = function(img) {
  var src = this.attr("src");
  var id = this;
  id.fadeToggle("fast", function(){
  id.attr("src", img);
  id.fadeToggle("fast");
  });
  return this;
  };

 })( jQuery );



(function( $ ) {

  $.fn.slideShow = function(array, time) {
  var i = -1;
  var num = array.length;
  var id=this;

  var interval = setInterval(function(){
  i++
  if(i>(num)-1){i=0}
  id.imageSwap(array[i]);
  },time);

  };

The page code:

<script>

$("#slideshow").slideShow([
"http://www.rta.nsw.gov.au/licensing/images/dkt_faqs/number1.gif",
"http://www.rta.nsw.gov.au/licensing/images/dkt_faqs/number2.gif",
"http://www.rta.nsw.gov.au/licensing/images/dkt_faqs/number3.gif",
"http://www.rta.nsw.gov.au/licensing/images/dkt_faqs/number4.gif"
], 1000);

</script>

<img id="slideshow" src=""/>
Dan
  • 41
  • 4
  • 1
    is it possibly somewhat related to something like this? (setInterval without an equivalent clearInterval) http://stackoverflow.com/questions/12266265/image-flickering-with-setinterval-function/12266329#12266329 – sajawikio Jan 06 '13 at 15:56
  • You may be calling `.slideShow()` more than once in your code either directly or indirectly – Alexander Jan 06 '13 at 15:58
  • maybe you need a return false ? – Michael Durrant Jan 06 '13 at 16:00
  • That's what I thought at first, but I've looked through all my code and can't find anywhere that i've called the function again. That's why I was hoping someone could possibly help me find that or another issue – Dan Jan 06 '13 at 16:01
  • 1
    I suspect fadeToggle() to be responsable of this unexpected behaviour. Have you got same result using fadeOut/fadeIn ? – A. Wolff Jan 06 '13 at 16:01
  • I don't see it getting any faster... – Guffa Jan 06 '13 at 16:04
  • I instrumented `setInterval` and `clearInterval` as fast as I could (code, copy, refresh, paste). I saw an immense number of `setInterval`s getting called, but not a single `clearInterval`. – John Dvorak Jan 06 '13 at 16:05

1 Answers1

2

I narrowed the problem here and noticed it was only happening when I switched tabs. So, a bit of searching revealed some things.

By design it seems that Chrome stacks up the setInterval calls. So, when you return to the inactive tab it just happens to run them in a row.

You can see some workarounds in other related questions in SO:

Community
  • 1
  • 1
Alexander
  • 23,432
  • 11
  • 63
  • 73