Patte Patte - 6 days ago 5
Javascript Question

javascript animate dosnt loop

I have a roulette game that looks like this:enter image description here

I want it to slow down more and more the further it goes, so i have this code:



$(document).ready(function() {
$("button").click(function() {
var moveTime = Math.floor(Math.random() * 1000) + 2000
var slowDown = 1000;
while (moveTime > 0) {
$("div").animate({
left: slowDown + "px"
});

if (slowDown > 0) {
slowDown--;
moveTime = 0;
}
slowDown--;
moveTime--;
}
});
});

div {
position: absolute;
float: left;
margin: 0 0 0 -8400px;
width: 10000px;
height: 100px;
background: repeating-linear-gradient(90deg, #DF0000, #DF0000 100px, #000000 100px, #000000 200px)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Start Animation</button>
<div></div>





But the problemis that it only play the animation 1 time. I have also tried with a infinityloop but that dont work either, same with pressing the button twice nothing happend the second time.

Answer

The problem with your code is that on successive clicks the div element is already at the left position you're trying to animate it to, so nothing appears to happen.

To fix this, reset the left position back to 0 before you run the animation again. Try this:

$(document).ready(function() {
  $("button").click(function() {
    var moveTime = Math.floor(Math.random() * 1000) + 2000
    var slowDown = 1000;
    var $div = $('div').css('left', 0); // < reset the position here

    while (moveTime > 0) {
      $div.animate({
        left: slowDown + "px"
      });

      if (slowDown > 0) {
        slowDown--;
        moveTime = 0;
      }
      
      slowDown--;
      moveTime--;
    }
  });
});
div {
  position: absolute;
  float: left;
  margin: 0 0 0 -8400px;
  width: 10000px;
  height: 100px;
  background: repeating-linear-gradient(90deg, #DF0000, #DF0000 100px, #000000 100px, #000000 200px)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Start Animation</button>
<div></div>