Issue
I have to preface I don't know a lot about Javascript so I built this by forking a Pen. I tried to find similar posts here, but the other posts mentioning lag didn't seem to align with my dilemma. It was lagging when I only had the one number, so I don't know if the second script had any effect on it. Here is all the code. Sometimes it gets stuck longer than the time placed in the Javascript. I want it to be consistently 1 second for the first number and 2 seconds for the second number.
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>
Solution
Why don't you use the $interval
service instead?
Also, I created a nextRand
function to ensure that the next random number is not the same as the previous. This demonstrates that the interval is running without issue.
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>
Answered By - Mr. Polywhirl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.