我正在尝试制定一个自定义指令,从 0 到 X 进行计数。我已经成功地工作了,但我似乎无法弄清楚如何提高计数。我面临的问题是最后的数字是 7/8 位数字,并且由于明显的原因加 1 并没有真正起作用。
这是三个独立的计数器,每个计数器都有不同的结束编号,目前已硬编码。
.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();
}]
}
}])
最佳答案
对于这样的事情我肯定会走相反的路。我将决定循环应该运行多长时间才能达到最终计数。假设我想在 10 秒内达到 5,000,000。这是 10,000 毫秒,我们决定每 10 毫秒循环一次。这使我们的循环计数为 1000。
所以我们现在有 1000 个循环才能达到 500 万个,即每个循环添加 5000 个。
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
显然,这会让计数器看起来很不自然。因此,您可以将增量值替换为非 10 次方的值。基本思想是让计数器在特定时间后停止。
您还可以在方程中添加一个速度因子,这样 1000 万和 500 万就不会同时结束。
我希望你明白了。
关于javascript - Angular JS 计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716256/