2

Actually in my project I have to reapeat few functions continiously,for that i have to use setinterval or call back.which one is the best way to repeat function either call back or setInterval.lightAnim() same kind of functions i have more than 8.If i use setInterval what will be happened and if use callback what will be happened with respect to browser.which way one is best.

1st way:Using setInterval

   <script>
        lightAnim();

        setInterval(lightAnim,5000);

         function lightAnim() {
            $(".bulb1").fadeIn(1000, function() {
              $(".bulb2").fadeIn(1000, function() {
               $(".bulb3").fadeIn(1000, function() {
                  $(".bulb4").fadeIn(1000, function() {
                    $(".bulb5").fadeIn(1000, function() {
                        $(".bulb6").fadeIn(1000);
                    })
                });
              });
           });
         })
       }
       </script>

2nd way:On complete i am calling again


  <script>

   lightAnim();

     function lightAnim() {
     $(".bulb1").fadeIn(1000, function() {
        $(".bulb2").fadeIn(1000, function() {
            $(".bulb3").fadeIn(1000, function() {
                $(".bulb4").fadeIn(1000, function() {
                    $(".bulb5").fadeIn(1000, function() {
                        $(".bulb6").fadeIn(1000);
                        lightAnim();
                    })
                });
            });
        });
    })
}
  </script>
Pioter
  • 465
  • 3
  • 8
  • 21

1 Answers1

1

The callback is definitely the better choice.

You don't need to sum the delays manually, and don't need to maintain it when updating the code. It's much more error-prone, as your code demonstrates: six one-second delays are not 5000 milliseconds. Your first snippet would animate the first and sixth bulb simultaneously.

Also, when you are animating a single element the animations would get chained onto jQuery's animation queue. If the timers deviate (and setInterval is known to drift over longer periods), then you could easily build up a very long queue (animations are scheduled faster than they are executed) which is not good for performance.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • can i have more callback function for various functions like more than 10 functions ? – Pioter Nov 25 '14 at 11:15
  • Sure. Just give them different names. Or even create them programmatically (but watch out for [closures in loops](http://stackoverflow.com/q/750486/1048572)) – Bergi Nov 25 '14 at 11:52
  • If i use 10 callback continuously ,in IE7 and IE8 Browser will get hang ? – Pioter Nov 25 '14 at 12:02
  • That's unusual (but nothing I wouldn't expect from IE) – Bergi Nov 25 '14 at 12:04