catandmouse
catandmouse

Reputation: 11809

setInterval doesn't work on .css method (no looping)

I'm using setInterval to try to rotate an image every 3 seconds and am using the below code:

jQuery:

$(document).ready(function(){
    setInterval(function(){ 
        $bird_wing_left.css({
            transform: "rotate(30deg)"
        }, 1000)
    }, 3000);
});

CSS:

.bird_wing_left {
    background: rgba(0, 0, 0, 0) url("../images/bird_wing_left.png") repeat scroll 0 0;
    height: 59px;
    left: 17px;
    position: absolute;
    top: 66px;
    width: 78px;
    transition: all 2s;
}

...but the animation only happens once and not every 3 seconds. If I try another method (not .css), it's ok. What could be the issue?

Upvotes: 1

Views: 137

Answers (2)

DavidVollmers
DavidVollmers

Reputation: 695

You rotate your image always to 30 degree and after the first rotation its rotation is 30° so it wont rotate anymore. You need to save the count of the degrees in a var and increase it with every iteration (also try to set it to 0 when it hits 360).

Upvotes: 0

James Thorpe
James Thorpe

Reputation: 32202

It's rotating to 30 degrees, not by 30 degrees. You need to keep track of how far it's already rotated:

$(document).ready(function(){
    var rotate = 0;
    setInterval(function(){ 
        rotate += 30;
        $bird_wing_left.css({
            transform: "rotate(" + rotate + "deg)"
        }, 1000)
    }, 3000);
});

Upvotes: 8

Related Questions