4

I need to set infinite rotating but it doesn't work.

function AnimateRotate(angle) {
    var $elem = $('.icon-repeat');

    $({deg: 0}).animate({deg: angle}, {
        duration: 5000,
        step: function(now) {
            $elem.css({
                transform: 'rotate(' + now + 'deg) infinite'
            });
        }
    });
}

That is my code, and this line transform: 'rotate(' + now + 'deg) infinite' .. if I remove infinite it works for one rotate, but I need to rotate infinite.. I have to write it in JS, I think...

user3809590
  • 175
  • 1
  • 2
  • 13

3 Answers3

3

Try this, You should set the "repeat" value. AnimateRotate(degree, repeatcount).

In your case set the repeatcount as "infinite".

function AnimateRotate(angle,repeat) {
    var duration= 1000;
    setTimeout(function() {
        if(repeat && repeat == "infinite") {
            AnimateRotate(angle,repeat);
        } else if ( repeat && repeat > 1) {
            AnimateRotate(angle, repeat-1);
        }
    },duration)    
    var $elem = $('.icon-repeat');

    $({deg: 0}).animate({deg: angle}, {
        duration: duration,
        step: function(now) {
            $elem.css({
                'transform': 'rotate('+ now +'deg)'
            });
        }
    });
}
AnimateRotate(45,"infinite");

Here the demo

Nandhakumar
  • 366
  • 2
  • 9
3

Here goes another answer, one that uses the complete callback of the animate() function instead of setInterval(), and that can be canceled:

function rotateForEver($elem, rotator) {
    if (rotator === void(0)) {
        rotator = $({deg: 0});
    } else {
        rotator.get(0).deg = 0;
    }

    return rotator.animate(
        {deg: 360},
        {
            duration: 5000,
            easing: 'linear',
            step: function(now){
                $elem.css({transform: 'rotate(' + now + 'deg)'});
            },
            complete: function(){
                rotateForEver($elem, rotator);
            },
        }
    );
}

You would then use it like this:

$(function() {
    var $rotator = rotateForEver($('.icon-repeat'));
    $('#some-button-to-cancel').click(function() {
        $rotator.stop();
    });
});
vyrp
  • 890
  • 7
  • 15
  • This solution is great because you can update the element while rotating without affecting the animation. Thanks! – Mihai Galan Apr 17 '23 at 19:29
0

You can wrap it with setInterval():

function AnimateRotate(angle) {
    var $elem = $('.icon-repeat');
    setInterval(function(){
       $({deg: 0}).animate({deg: angle}, {
          duration: 5000,
          step: function(now) {
            $elem.css({
                transform: 'rotate(' + now + 'deg) infinite'
            });
          }
       });
    }
}

and call it like:

AnimateRotate(360);

Updated demo as suggested by bemol.

Jai
  • 74,255
  • 12
  • 74
  • 103