Reputation: 1970
I am trying to make a custom directive to count up from 0 to X. I have it successfully working however i cant seem to figure out how to improve the count. the problem I'm facing is that the end numbers is a 7/8 digit number and counting up by 1 is not really working for obvious reasons.
It is three separate counters that each one will have a different end number which is hard coded for now.
.directive('cuImpactCounter', ['$compile', function ($compile) {
return {
restrict: 'E',
replace: false,
scope: {},
template: '<div class="row">' +
'<div class="col d-flex text-center flex-column">' +
'<div><p>Test 1</p></div>' +
'<div><p>{{ interestSavedMillis }}</p></div>' +
'</div>' +
'<div class="col d-flex text-center flex-column">' +
'<div><p>Test 2</p></div>' +
'<div><p>{{ interestEarnedMillis }}</p></div>' +
'</div>' +
'<div class="col d-flex text-center flex-column">' +
'<div><p>Test 3</p></div>' +
'<div><p>{{ savingsEarnedMillis }}</p></div>' +
'</div>' +
'</div>',
controller: ['$scope', function ($scope) {
$scope.interestSavedMillis = 0;
var interestSaved = 15016400;
var i = 0;
function interestSavedTimeLoop() {
setTimeout(function() {
$scope.interestSavedMillis++;
$scope.$digest();
i++;
if (i < interestSaved) {
interestSavedTimeLoop();
}
}, 1);
}
interestSavedTimeLoop();
//
$scope.interestEarnedMillis = 0;
var interestEarned = 12367690;
var x = 0;
function interestEarnedTimeLoop() {
setTimeout(function () {
$scope.interestEarnedMillis++;
$scope.$digest();
x++;
if (x < interestEarned) {
interestEarnedTimeLoop();
}
}, 1);
}
interestEarnedTimeLoop();
$scope.savingsEarnedMillis = 0;
var savingsEarned = 34819566;
var y = 0;
function savingsEarnedTimeLoop() {
setTimeout(function () {
$scope.savingsEarnedMillis++;
$scope.$digest();
y++;
if (y < savingsEarned) {
savingsEarnedTimeLoop();
}
}, 1);
}
savingsEarnedTimeLoop();
}]
}
}])
Upvotes: 0
Views: 684
Reputation: 1058
For someting like this I would definitely go the opposite way. I will decide on how long the loop should run to reach the final count. Say I want to reach 5,000,000 in 10 seconds. That's 10,000 milliseconds and let's decide we will loop every 10 milliseconds. That gives us the loop count to be 1000.
So we now have 1000 loops to reach 5 million ie, add 5000 on each loop.
let counter = 0;
setTimeout(function() {
counter +=5000;
if(counter > interestSaved)
counter = interestSaved;
$scope.interestSavedMillis = counter;
$scope.$digest();
if (counter < interestSaved) {
interestSavedTimeLoop();
}
}, 10); //10 millisecond loop
Obviously, this will make the counter look artificial. So you can replace the increment value to something that is not power of 10. The basic idea is to have the counter stop after particular time.
You can also add a speed factor into the equation, so that 10 milliona and 5 million don't end at same time.
I hope you got the idea.
Upvotes: 1