Jquery how to fire the same event every 5 seconds

I built a simple carousel with a left and right scroll. Now I want to scroll automatically every 5 seconds. Here is my code:

function carousel(){ $j('#carousel_ul li:first').before($j('#carousel_ul li:last')); $j('#right_scroll img').click(function(){ var item_width = $j('#carousel_ul li').outerWidth() + 10; var left_indent = parseInt($j('#carousel_ul').css('left')) - item_width; $j('#carousel_ul:not(:animated)').animate({'left' : left_indent},800, 'easeOutExpo',function(){ $j('#carousel_ul li:last').after($j('#carousel_ul li:first')); $j('#carousel_ul').css({'left' : '-750px'}); }); }); $j('#left_scroll img').click(function(){ var item_width = $j('#carousel_ul li').outerWidth() + 10; var left_indent = parseInt($j('#carousel_ul').css('left')) + item_width; $j('#carousel_ul:not(:animated)').animate({'left' : left_indent},800, 'easeOutExpo',function(){ $j('#carousel_ul li:first').before($j('#carousel_ul li:last')); $j('#carousel_ul').css({'left' : '-750px'}); }); }); } 

How do I achieve this? Thanks in advance:)

Mauro

+4
source share
2 answers

You can use setInterval. Take a look:

 window.setInterval(event, 5000); 

And the function event will be

 function event() { $j("#right_scroll img").click(); } 

EDIT:

Tks @cris! setTimeout calls only once. I changed to setInterval.

Tks @bears! Now I pass the setInterval function.

+11
source
 var i = setInterval(carousel, 5000) 

And to stop it later:

 clearInterval(i); 
+12
source

All Articles