简体   繁体   中英

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM