0

The code below should move the element "box" down by "speed" pixels every second, and "speed" should decrease by 0.1 every second. This should give the illusion of slowing movement. If anyone knows how to fix this code - or offer a different solution - it would be greatly appreciated.

function move() {
    var pos = 318;
    
    for (var speed = 5; speed > 0; speed -= 0.1) {
        setTimeout(function() {
            pos -= speed;
            document.getElementById("box").style.bottom = pos + "px";
        }, 1000);
    }
}

1 Answers1

1

The setTimeout inside the for loop doesn't actually create a delay between iterations as you'd expect, rather it simply does all of the function executions after one second. Instead, you should create another function inside the move() function that calls itself with setTimeout(), or use setInterval().

Using setTimeout:

function move() {
    var pos = 0;
    
    var speed = 5;
    function moveBox() {
      if (speed <= 0) {console.log("done"); return;}
      speed -= 0.1;
      pos += speed; // done backwards for visibility
      document.getElementById("box").style.top = pos + "px";
      setTimeout(moveBox, 25) //sped up for convenience
    }
    moveBox();
}
move();
#box {
  position: absolute;
  height: 1em;
  width: 1em;
  background-color: black;
}
<div id="box" style="bottom: 318px"></div>
Lemondoge
  • 959
  • 4
  • 17
  • 2
    Do you know about the "new" way to make a [`sleep()` function in ES6](https://stackoverflow.com/a/64996707/13561410)? It's easier to read, and can easily be used without providing a callback. – Oskar Grosser Nov 30 '20 at 02:18