angularjs JavaScript数字生成器滞后,是什么导致了这种滞后?[已关闭]

rlcwz9us  于 12个月前  发布在  Angular
关注(0)|答案(1)|浏览(97)

已关闭,此问题需要details or clarity。它目前不接受回答。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

2个月前关闭。
Improve this question
我不得不前言,我不知道很多关于JavaScript,所以我建立了这个分叉笔。我试图在这里找到类似的帖子,但其他提到滞后的帖子似乎与我的困境不一致。当我只有一个数字的时候,它是滞后的,所以我不知道第二个脚本是否对它有任何影响。这里是所有的代码。有时候,它被卡住的时间比JavaScript中放置的时间还要长。我希望第一个数字始终为1秒,第二个数字为2秒。

var app = angular.module('myApp', []);

app.controller('MyRngCtrl', function($scope, $timeout) {
  $scope.rngESUS = 0;
  (function update() {
    $timeout(update, 1000 * 1);
    $scope.rngESUS = Math.round((Math.random() * 5) + 1);
  }());
});

app.controller('MyRngCtrl2', function($scope, $timeout) {
  $scope.rngESUS2 = 0;
  (function update() {
    $timeout(update, 1000 * 2);
    $scope.rngESUS2 = Math.round((Math.random() * 5) + 1);
  }());
});
.number {
  font-size: 25px;
  font-weight: 800;
  font-family: arial, sans-serif;
  text-align: center;
  color: red;
}

h4 {
  font-size: 20px;
  font-family: arial, sans-serif;
  text-align: center;
  margin: 1rem 0 0.5rem 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body ng-app="myApp">

  <h4>ONE SECOND PUNCH</h4>
  <div class="number" ng-controller="MyRngCtrl">
    {{rngESUS}}
  </div>

  <h4>TWO SECOND PUNCH </h4>
  <div class="number" ng-controller="MyRngCtrl2">
    {{rngESUS2}}
  </div>

</body>
flmtquvp

flmtquvp1#

为什么不使用$interval服务呢?
另外,我创建了一个nextRand函数,以确保下一个随机数与前一个不同。这表明间隔运行没有问题。

var app = angular.module('myApp', []);

function randRange(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function nextRand(curr) {
  let next;
  do { next = randRange(1, 6); }
  while (next === curr);
  return next;
}

app.controller('MyRngCtrl', function($scope, $interval) {
  $scope.rngESUS = 0;
  $interval(function () {
    $scope.rngESUS = nextRand($scope.rngESUS);
  }, 1000);
});

app.controller('MyRngCtrl2', function($scope, $interval) {
  $scope.rngESUS2 = 0;
  $interval(function () {
    $scope.rngESUS2 = nextRand($scope.rngESUS2);
  }, 2000);
});
.number {
  font-size: 25px;
  font-weight: 800;
  font-family: arial, sans-serif;
  text-align: center;
  color: red;
}

h4 {
  font-size: 20px;
  font-family: arial, sans-serif;
  text-align: center;
  margin: 1rem 0 0.5rem 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body ng-app="myApp">

  <h4>ONE SECOND PUNCH</h4>
  <div class="number" ng-controller="MyRngCtrl">
    {{rngESUS}}
  </div>

  <h4>TWO SECOND PUNCH </h4>
  <div class="number" ng-controller="MyRngCtrl2">
    {{rngESUS2}}
  </div>

</body>

相关问题