jquery how to fire the same event every 5 seconds

时间秒杀一切 提交于 2019-12-06 04:11:54

问题


I've built a simple carousel with left and right scroll. Now I want to scroll automatically every 5 seconds. Here's 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 that? Thanks in advance :)

Mauro


回答1:


You can use setInterval. Look:

window.setInterval(event, 5000);

And function event would be

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

EDIT:

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

Tks @bears! Now I pass a function to setInterval.




回答2:


var i = setInterval(carousel, 5000)

And to stop it later:

clearInterval(i);


来源:https://stackoverflow.com/questions/3549853/jquery-how-to-fire-the-same-event-every-5-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!