Jothi Kannan Jothi Kannan - 6 months ago 44
Javascript Question

Jquery setInterval and clearInterval

I want to highlight a list items one by one, once it reaches the final list item, highlight should be removed

setInterval is working, but when i use clearInterval to remove the Interval it doesn't work

<ul>
<li><a href="#" class="anchor">I am an anchor</a></li>
<li><a href="#" class="anchor">I am an anchor</a></li>
<li><a href="#" class="anchor">I am an anchor</a></li>
<li><a href="#" class="anchor">I am an anchor</a></li>
<li><a href="#" class="anchor">I am an anchor</a></li>
</ul>


var $anchors = $('a.anchor'), counter = 0;
var interval;
interval = setInterval(function(){
$anchors.removeClass('highlight');
$anchors.eq(counter++ % $anchors.length).addClass('highlight');
if($anchors.length==5){
clearInterval(interval);
}
}, 4000);


anyway to clear the interval when it reaches the final list item ?

Fiddle link : DEMO

Update : Sorry i was wrong in code, corrected the code, still same issue

Answer

If You want to highlight last one :

 var $anchors = $('a.anchor'), counter = 0;
    var interval;
    interval = setInterval(function(){
      $anchors.removeClass('highlight');
      $anchors.eq(counter++ % $anchors.length).addClass('highlight');
    	if($anchors.length == counter){
    		clearInterval(interval);
      }
    }, 1000);
.highlight{
    color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
</ul>


If you don't wont to highlight last one

var $anchors = $('a.anchor'), counter = 0;
var interval;
interval =setInterval(function(){
  $anchors.removeClass('highlight');
  if($anchors.length==counter){
	  clearInterval(interval);
      return;
   }
  $anchors.eq(counter++ % $anchors.length).addClass('highlight');
   
}, 1000);
.highlight{
    color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
  <li><a href="#" class="anchor">I am an anchor</a></li>
</ul>