Why does this jQuery function fire twice?

So, I'm trying to create a small jQuery plugin for personal use. I have a function, but the setInterval () function is fired twice for some reason, and I cannot understand why. At first it seems that it doesn’t work twice, but I know by testing (adding a warning for each interval trigger) that it works twice, using the example here you can see that it is gradually getting faster and faster (after about 2 minutes it will be very fast), this is the result of a double shot.

Can someone please help me how to fix this?

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); }; 

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=""/> 
+4
source share
1 answer

I narrowed down the problem here and noticed that this only happens when switching tabs. So, some searches revealed some things.

By design, it seems like Chrome combines calls to setInterval . Therefore, when you return to the inactive tab, they simply run in a line.

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

+1
source

All Articles