Javascript: SetInterval not repeating style changes

Viewed 36

As a little break from my rhythm game I've been making with HTML/JavaScript, I decided to make a recreation of the Heatman bossfight from Megaman 2. I'm using setInterval to make the code loop infinitely. As a test, I made a function called moveHeat which adds 10 Heatman's left style value. When I run the setInterval with the function, the image (heatman) only moves once. What am I doing wrong?

Here is the code rn:

function moveHeat() {
  document.getElementById("hetman").style.left += "10px";
  return (document.getElementById("hetman").style.left)
}

var heatInterval = setInterval(function() {
  moveHeat()
}, 10);
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
}

#hetman {
  position: relative;
  left: 10px;
}
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <img src="https://via.placeholder.com/300" id="hetman">
</body>

1 Answers

As already stated by someone within the comments, you can not concatenate a string to the .style.left. The concatenating as you have it would look like 10px10px10px....

So you need a variable that you multiplier that you raise with every interval. That multiplier you sent to your function and multiply it with the 10px.

let i = 1;

function moveHeat(i) {
  document.getElementById("hetman").style.left = `${i * 10}px`;
  return (document.getElementById("hetman").style.left)
}

var heatInterval = setInterval(function() { 
  moveHeat(i);
  i++;
}, 10);
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
}

#hetman {
  position: relative;
  left: 10px;
}
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <img src="https://via.placeholder.com/300" id="hetman">
</body>

Related