在JavaScript中减去计数器

时间:2015-12-06 08:23:41

标签: javascript

所以我有一个运行计数器,从0到20.000。

但我想要的是当用户按下按钮时,计时器会回到250。

因此,例如,计时器为350,它应该回到100。

我尝试了以下代码:

我的计时器:

  var num = 0;
  var max = 20000;

  function resourcesCounter() {
    if (num > max) {
      window.clearTimeout ("tim");
    }
    else {
      document.getElementById('wood').innerHTML = num;
      document.getElementById('iron').innerHTML = num;
      document.getElementById('clay').innerHTML = num;
      num ++;
      var tim = window.setTimeout("resourcesCounter()", 100);
    }
  }
resourcesCounter();

按下按钮后,返回250:

if(buildingLevel == 'Level 1' && building == 'mainBuilding') {
      if(wood >= 250 && iron >= 150 && clay >= 200) {
        document.getElementById('level-1').innerHTML = 'Level 2';
        document.getElementById('wood').innerHTML = wood - 250;
      } else {
        console.log('Not enough resources');
        console.log(wood + ' ' + iron + ' ' + clay);
      }
    }

但是,此代码不起作用。它会在一瞬间更改倒计时,然后返回其原始值。

3 个答案:

答案 0 :(得分:1)

我已在this小提琴中实现了您的功能。请看看它是否适合您:

function startTimer(){
  return setInterval(function(){
    var counter = document.getElementById("counter-container");
    var count = parseInt(counter.textContent.trim());
    count += 1;
    counter.textContent = count;
  }, 100);
};

var timer = startTimer();

var resetButton = document.getElementById('reset-by-250');;
resetButton.addEventListener("click", function(){
  clearInterval(timer);
  var counter = document.getElementById("counter-container");
  var count = parseInt(counter.textContent.trim());
  count -= 250;
  if(count < 0){
    count = 0;
  }
  counter.textContent = count;
  timer = startTimer();
});

答案 1 :(得分:0)

var num = 0;
  var max = 20000;

  function resourcesCounter() {
    if (num > max) {
      window.clearTimeout ("tim");
    }
    else {
      document.getElementById('wood').innerHTML = num;
      document.getElementById('iron').innerHTML = num;
      document.getElementById('clay').innerHTML = num;
      num ++;
      var tim = window.setTimeout("resourcesCounter()", 100);
    }
  }
function clickbtn(){
num=num-250;
}
<button onclick="clickbtn()">button</button>

答案 2 :(得分:0)

按下按钮时,您永远不会设置num。它将在再次调用resourcesCounter时使用。

if(buildingLevel == 'Level 1' && building == 'mainBuilding') {
  if(wood >= 250 && iron >= 150 && clay >= 200) {
    document.getElementById('level-1').innerHTML = 'Level 2';
    // Change num so resourcesCounter() will have the updated value
    num -= 250;
    document.getElementById('wood').innerHTML = num;
  } else {
    console.log('Not enough resources');
    console.log(wood + ' ' + iron + ' ' + clay);
  }
}