我正在尝试创建一个简单的拖动竞赛动画。单击按钮,汽车图像将在页面上移动,直到每个图像到达特定位置。下面的代码适用于每次单击使汽车随机移动一段随机距离的单击,但是我希望单击一次可在循环中重复该运动。我尝试将其放入参考x的值的while循环中,但它不起作用。有任何想法吗。



<html>
<head>
  <meta charset="utf-8">
  <title>Race Car</title>
</head>
<body>
  <input type="button" id="move" value="race time" onClick="race()" />
  <div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
  <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
  <script>
    //Get car position coordinates
    x = $("#car").offset().left;
    y = $("#car").offset().top;

    //Move car across screen by resetting car position coordinates
    var race = function() {
      var delay = 1000;

      setTimeout(function() {
        $("#car").css({
          left: x += Math.floor(Math.random() * 50),
          top: y
        });
        x = $("#car").offset().left;
      }, delay);
    };
  </script>
</body>

</html>

最佳答案

您正在寻找setInterval

setTimeout在x毫秒后运行一次函数。

setInterval每x毫秒运行一次函数。

确保将时间间隔存储在可以访问的变量(var timer = setInterval(fn, ms))中,然后在要停止时间间隔(clearInterval(timer))时将其清除。

关于javascript - 延迟循环代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48118038/

10-12 00:09
查看更多