Javascript/jQuery Is it possible to break out of a function through another function?

3.1k views Asked by At

I'm doing a script that rotates li's in a given ul. I'd like to know whether it is possible to break a recursion I have when one of the li's is hovered. Ideally I'd create a boolean whether the recursion should continue or not, as I'd like to have this to break when I have a video embed in it in the future. I've just started it so this is basically what I've got.

HTML:

    <script type="text/javascript">
 $(document).ready(function(){
  $("#ulRotator").rotate();
 });
    </script>
    </head>
    <body>
 <ul id="ulRotator" style="width:500px; height:500px;">
     <li style="background-color:red;"></li>
        <li style="background-color:blue;"></li>
        <li style="background-color:black;"></li>
        <li style="background-color:green;"></li>
        <li style="background-color:grey;"></li>
    </ul>

</body>

Javascript:

    (function( $ ){

 var rotator;
 var rotatorLi;

 $.fn.rotate = function() {
  rotator = this;
  rotatorLi = rotator.children('li');

  rotatorLi.css('width',rotator.css('width')).css('height',rotator.css('height'));
  rotator.addClass('rotator');
  $(rotatorLi[0]).addClass('current');

  moveSlides('right');
 };


 moveSlides = function(direction){
  var current = $(rotator).find('li.current');  
  var currentPosition = $(rotatorLi).index(current);
  var slideCount = $(rotatorLi).length - 1;

  var next;
  if (direction == 'right'){
   if(currentPosition == slideCount){
    next = rotatorLi[0];
   }else{    
    next = rotatorLi[currentPosition+1];
   }
  }
  else if (direction == 'left'){
   if(currentPosition == 0){
    next = rotatorLi[slideCount];
   }else{    
    next = rotatorLi[currentPosition-1];
   } 
  }

  $(current).delay(6000).fadeOut(500,function(){
   $(current).removeClass('current');
   $(next).addClass('current');
   $(next).css('display','block');
   moveSlides(direction);
  });
 };
    })( jQuery );

CSS

    .rotator li
    {
 position:absolute;
 z-index:0;
 display::block !important;
 list-style-type:none;
    }
    li.current
    { 
 z-index:1 !important;
    }

Also note that I consider myself a huge newbie when it comes to Javascript, I might be going around this in a very idiotic way without me knowing it, any pointers would be appreciated. Cheers.

1

There are 1 answers

6
Fabian On BEST ANSWER

I woul set a variable like abort to true using a public function in the mouseover and check it in the first line of moveSlides. If it's set to true simply return out of the function.