我目前有以下代码,我想知道如何在弹出窗口模式达到200000之后使它弹出,而不是继续到500000,而是停止计数器。
<div class="available-credits" id="value">500000</div>
function animateValue(obj, start = 0, end = null, duration = 600000) {
if (obj) {
var textStarting = obj.innerHTML;
end = end || parseInt(textStarting.replace(/\D/g, ""));
var range = end - start;
var minTimer = 50;
var stepTime = Math.abs(Math.floor(duration / range));
stepTime = Math.max(stepTime, minTimer);
var startTime = new Date().getTime();
var endTime = startTime + duration;
var timer;
function run() {
var now = new Date().getTime();
var remaining = Math.max((endTime - now) / duration, 0);
var value = Math.round(end - (remaining * range));
obj.innerHTML = textStarting.replace(/([0-9]+)/g, value);
if (value == end) {
clearInterval(timer);
}
}
timer = setInterval(run, stepTime);
run();
}
}
animateValue(document.getElementById('value'));
答案 0 :(得分:0)
返回是您用来解决这种情况的方法。 您可以使用一些数学运算来估算下一个迭代值,并使其更精确。
<div class="available-credits" id="value">500000</div>
function animateValue(obj, start = 0, end = null, duration = 600000, limit = 10000) {
if (obj) {
var textStarting = obj.innerHTML;
end = end || parseInt(textStarting.replace(/\D/g, ""));
var range = end - start;
var minTimer = 50;
var stepTime = Math.abs(Math.floor(duration / range));
stepTime = Math.max(stepTime, minTimer);
var startTime = new Date().getTime();
var endTime = startTime + duration;
var timer;
function run() {
var now = new Date().getTime();
var remaining = Math.max((endTime - now) / duration, 0);
var value = Math.round(end - (remaining * range));
obj.innerHTML = textStarting.replace(/([0-9]+)/g, value);
if(value >= limit)
{
obj.innerHTML = limit;//cheat
clearInterval(timer);
return;
}
if (value == end) {
clearInterval(timer);
}
}
timer = setInterval(run, stepTime);
run();
}
}
animateValue(document.getElementById('value'));