Dan
Dan

Reputation: 41

Why is this my jQuery function firing twice?

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=""/>

Upvotes: 4

Views: 527

Answers (1)

Alexander
Alexander

Reputation: 23537

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:

Upvotes: 2

Related Questions