简体   繁体   中英

jquery simple image changer

Hello everyone I have this code to change multiple images like slideshow

function test() {
   $(".topimg img").first().appendTo('.topimg').fadeOut(1000);
   $(".topimg img").first().fadeIn(1000);
   setTimeout(test, 7000);
}
test();

But I have one problem when I minimize browser or change tab and when I back image are changing too fast.How can I fix that and please fix this code do not give me another one with javascript or anything this is the simple one.

Please try this one:

 function test() {
       $(".topimg img").first().appendTo('.topimg').fadeOut(1000);
       $(".topimg img").first().fadeIn(1000);
 }

 setTimeout(function(){test();}, 7000);

The rendering is paused while tab is not in view. It would be appropriate to pause the logic as well, so the browser does not need to catch up with the events when the page comes into view again.

I'm sure there are ways to detect this in other browsers, but I've never used those, so no reference comes to mind for those.

you can use setInterval instead of setTimeout . setInterval will call test after each 7000 milli seconds. if you want run test immediately you can call it just after setInteval;

I added inteval variable to check if setInterval is already running if so don't call setInterval.

   if(window.inteval){
      return
   }
    function test() {
       $(".topimg img").first().appendTo('.topimg').fadeOut(1000);
       $(".topimg img").first().fadeIn(1000);
    }
    if(!window.inteval){
         window.inteval = setInterval(test, 7000);
   }

Same way you can put check on your code

   function test() {
       $(".topimg img").first().appendTo('.topimg').fadeOut(1000);
       $(".topimg img").first().fadeIn(1000);
       window.interval = setTimeout(test, 7000);
    }
   if( !window.interval){
       test();
   }

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