开发者

Moving a carousel using setInterval

开发者 https://www.devze.com 2023-03-29 09:13 出处:网络
I am trying to use the following code to move carousel elements through every second: function moveCarousel(){

I am trying to use the following code to move carousel elements through every second:

function moveCarousel(){
        var x = $('.carousel_title.active');
        var next = x.next();
   开发者_Python百科     x.removeClass('active');
        next.addClass('active');

    }

    setInterval(moveCarousel(),1000);

but two things seem to go wrong:

  1. The first cycle happens instantly
  2. No further cycles occur

Where have I gone wrong?


you should remove the braces on your last line

function moveCarousel()
{
        var x = $('.carousel_title.active');
        var next = x.next();
        x.removeClass('active');
        next.addClass('active');

    }

    setInterval(moveCarousel,1000);

In this case you are passing a function (moveCarousel) to a nother function (setInterval) and thus the function is not to be executed (that's what the braces are for) but to be passed like an object.

Your original code was passing undefined (because moveCarousel does not return anything) to the setInterval function - and setInterval takes a function as it's first parameter - not undefined

You could also do this:

setInterval(function () { moveCarousel(); }, 1000);

where you construct an anonymous function to call moveCarousel.


You're calling the function where you should pass the function itself:

function moveCarousel(){
    var x = $('.carousel_title.active');
    var next = x.next();
    x.removeClass('active');
    next.addClass('active');

}

setInterval(moveCarousel, 1000); // no () here

Currently, you call the function immediately and it evaluates to:

setInterval(undefined, 1000);

(the function returns nothing so it returns undefined), which is not what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消