Home > Enterprise >  Why does this element not travel at a consistent speed?
Why does this element not travel at a consistent speed?

Time:04-14

I'm making a program that moves an element to a random point at a speed of 50px per second (and loops once it reaches that point). I've done the math, but the speeds it travels are inconsistent.

// for some reason i need to put all the code in a function, so that's what this bit is
window.onload = doit;

function doit() {
  var dief = document.getElementById('he');

  //chooses a random number within the width of the page (px):
  var mh = Math.floor(Math.random() * window.innerWidth);

  //sets the time it should take to travel the random distance going 50px per second (t=d/v):
  time = mh / 50

  //this sets the amount of time it takes for the transition from one point to another to occur:
  dief.style.transition = "left "   time   "s linear";

  //this sets the position:
  dief.style.left = mh   "px";
  setTimeout(doit, time * 1000);
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>

<body>
  <div id="he" style="position: absolute; left: 0px;">hey</div>
</body>

</html>

CodePudding user response:

The distance to travel isn't mh. It's mh minus the current left of the element.

Here's how you might do this:

window.onload = () => doit(0);

function doit(currentLeft) {
  var dief = document.getElementById('he');
  var mh = Math.floor(Math.random() * window.innerWidth);
  var time = Math.abs(mh - currentLeft) / 50
  dief.style.transition = "left "   time   "s linear";
  dief.style.left = mh   "px";
  setTimeout(() => doit(mh), time * 1000);
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>

<body>
  <div id="he" style="position: absolute; left: 0px;">hey</div>
</body>

</html>

  • Related