如何在特定数量处停止JavaScript计数器

时间:2019-03-13 13:54:03

标签: javascript tampermonkey

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

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

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

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

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') 

2 个答案:

答案 0 :(得分:1)

在您的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);

答案 1 :(得分:0)

可以通过清除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;
}