DecstarG DecstarG - 3 months ago 14
HTML Question

Uncaught SyntaxError: missing ) after argument list (setInterval)

I am making a program that when you click a button an object spins and this code has an errror:

function spin(object) {
setInterval(object.style.transform += "rotate(5deg)", 3000)
}


First why and how do I fix this. Second. Is there any way to refine this code? Third I am using google chrome.

Answer

As per comment, you cannot simply pass an expression to setInterval, only a function.

function spin(object) {
    setInterval(function() {
        object.style.transform += "rotate(5deg)"
    }, 3000);
}

var el = document.getElementsByTagName("div")[0];
spin(el);
div {
  width: 100px;
  height: 100px;
  border: 3px solid red;
}
<div>
hello
</div>

As you can see, this works. However, if you look at the code what is happening is that the rotate string is appended to the transform property each time. Resulting in stuff like this:

transform: rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg) rotate(5deg);

That's not what you want. Instead, increment only the number or use CSS animations.

Example with incrementing degrees

function spin(object) {
  var i = 0;
  setInterval(function() {
    i++;
    object.style.transform = 'rotate(' + i * 5 + 'deg)';
  }, 3000);
}

var el = document.getElementsByTagName("div")[0];
spin(el);
div {
  width: 100px;
  height: 100px;
  border: 3px solid red;
}
<div>
  hello
</div>

Keyframes (CSS animation) example

div {
  width: 100px;
  height: 100px;
  border: 3px solid red;
  transform-origin: center center;
  /* (360 / 5 degree steps) * 3s per step = 216s */
  animation: spin linear 216s infinite forwards;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<div>
  hello
</div>