Artdark92
Artdark92

Reputation: 121

setInterval() not working with rotate

I have an image. I have written some code that will rotate it over en over, but the setInterval() function is not working.

Please can you tell me why?

var star = document.getElementById('star');
setInterval(function() {star.style.transform = "rotate(10deg)"; },10);

Upvotes: 0

Views: 1882

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

You need to increment the degree value on each function call, simply do it using a variable. In your case it will always stay on 10degree rotate.

DEMO:

var star = document.getElementById('star'),
  deg = 10;
setInterval(function() {
  star.style.transform = "rotate(" + deg + "deg)";
  deg = (deg + 10) % 360
}, 10);
#star {
  width: 100px;
  height: 100px;
  background: red;
}
<div id="star"></div>


You can use css animation here

@keyframes anim {
  0% {
    transform: rotate(0deg);
  }25% {
    transform: rotate(90deg);
  }50% {
    transform: rotate(180deg);
  }75% {
    transform: rotate(270deg);
  }100% {
    transform: rotate(360deg);
  }
}

#star {
  width: 100px;
  height: 100px;
  background: red;
  animation: anim .36s infinite;
}
<div id="star"></div>

Upvotes: 3

Ali Mamedov
Ali Mamedov

Reputation: 5256

Small sample:

var ready = function() {
 
  var 
    star = document.getElementById('star'),
    degree = 0;
  
  setInterval(function() {
    
    /* Every 10ms degree variable increase its value by 1 */
    star.style.transform = "rotate(" + ++degree +"deg)"; }, 10
  );
};
#star {
  
  margin-left: 100px; 
  margin-top: 40px; 
  width: 60px; 
  border: 1px solid; 
  padding: 20px; 
}
<body onload="ready()">
  <div id="star">
    <h1>Yay!</h1>
  </div>
</body>

Upvotes: 0

Related Questions