Javascript Question

How to make the time interval on the slider?

My sidebar

Here I have some

div
, with
ul
list

<div class="slider">
<ul>
<li><img src="http://127.0.0.1/anim/wp-content/uploads/2016/slider/cat1.jpg" alt=""></li>
<li><img src="http://127.0.0.1/anim/wp-content/uploads/2016/slider/cat2.jpg" alt=""></li>
<li><img src="http://127.0.0.1/anim/wp-content/uploads/2016/slider/cat3.jpg" alt=""></li>
</ul>
</div>


And jQuery, this slider working only after clicking, but I need after clicking and after 5 second interval, how I can fix it?

$(document).ready(function() {
$(".slider").each(function () {
var obj = $(this);
$(obj).append("<div class='nav'></div>");
$(obj).find("li").each(function () {
$(obj).find(".nav").append("<span rel='"+$(this).index()+"'></span>");
$(this).addClass("slider"+$(this).index());
});
$(obj).find("span").first().addClass("on");
});
});

function sliderJS (obj, sl) { // slider function
var ul = $(sl).find("ul");
var bl = $(sl).find("li.slider"+obj);
var step = $(bl).width();
$(ul).animate({marginLeft: "-"+step*obj}, 500);
}

$(document).on("click", ".slider .nav span", function() { // slider click navigate
var sl = $(this).closest(".slider");
$(sl).find("span").removeClass("on");
$(this).addClass("on");
var obj = $(this).attr("rel");
sliderJS(obj, sl);
return false;
});


How to make the interval every 5 seconds?

Answer
autoplayInterval = setInterval( moveToNext, 5000 );

function moveToNext()
{
  var curIndex = parseInt( $(".slider .nav span.on").attr("rel") );
  var totalSlides = $(".slider .nav span").length;
  var nextIndex = curIndex + 1;

  if( nextIndex >= totalSlides )
  {
    nextIndex = 0;
  }//if

  $(".slider .nav span.on").removeClass("on");
  $(".slider .nav span").eq( nextIndex ).addClass("on").trigger("click");

}//moveToNext();