Artdark92 Artdark92 - 7 months ago 53
Javascript Question

setInterval() not working with rotate

I have an image. I vant to rotate it over en over. But set interval function is not working. Please can you tell me why?

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

Answer

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>