如何在特定数字停止 javascript 计数器

How to stop javascript counter at specific number

我有这个 javascript tampermonkey 代码可以在亚马逊上使用。它所做的只是计算您的礼品卡余额,让我看起来像是在收钱。我想知道是否可以让它停在特定的数字上。

var oof = document.getElementById("gc-ui-balance-gc-balance-value");

var lastCount = localStorage.getItem("lastCount");

oof.innerText = '$' + lastCount || "000";

function animateValue(id) {
    var obj = document.getElementById(id);
    var current = parseInt(localStorage.getItem("lastCount")) || 10000;

    setInterval(function () {
        var nextCount = current++;
        localStorage.setItem("lastCount", nextCount);
        obj.innerText = '$' + nextCount;
    }, 0.1);
}

animateValue('gc-ui-balance-gc-balance-value') 

可能是通过清除 current 达到特定值时的间隔

function animateValue(id) {
  // rest of the code
  let interval = setInterval(function() {
    var nextCount = current++;
    localStorage.setItem("lastCount", nextCount);
    obj.innerText = '$' + nextCount;
  }, 0.1);

  if (current === requiredVal) {
    clearInterval(interval)
  }
  return current;
}

在您的 setInterval 回调中使用 clearInterval,这样每次调用回调时,您都可以检查新计数是否已达到阈值,如果已达到则清除计时器。

如果您在回调之外检查值,则不会在每次计数增量时调用逻辑。

function animateValue(id) {
    var obj = document.getElementById(id);
    var current = parseInt(localStorage.getItem("lastCount")) || 10000;

    var interval = null;
    var maxCount = 1000;
    var callback = function() {
        var nextCount = current++;
        if (nextCount === maxCount) {
            clearInterval(interval);
        }
        localStorage.setItem("lastCount", nextCount);
        obj.innerText = '$' + nextCount;
    }
    interval = setInterval(callback, 0.1);
}

这是一个演示:

let current = 0;
let interval = null;

const callback = () => {
    let nextCount = current++;
    console.log(nextCount);
    if (nextCount === 5) {
        clearInterval(interval);
    }
}

interval = setInterval(callback, 100);