Skip to content
Advertisement

Cleaner way instead of running the function every second

I made a simple Coin System with JavaScript. And to make Upgrades, I made a button that gets enabled when it’s over 10. To make this permanently I run this function every millisecond with this:

window.setInterval(function(){
  // My code is here
}, 1);

Anyway, is there a cleaner way to run this system without running the function every millisecond? It looks like this isn’t clean code

Here is the code I made for the Coin-System-Thing:

var numberCounter = 0;
var number = document.getElementById("number");

function plusOne() {
    numberCounter++;
  number.innerHTML = numberCounter;
}

function minusOne() {
    numberCounter--;
  number.innerHTML = numberCounter;
}


/* Disable Buttons when below 10 */

window.setInterval(function(){
if(number.innerHTML <=9){
  document.getElementById("enableMe").disabled = true;
} else {
  document.getElementById("enableMe").disabled = false;
}
}, 1);
<button onclick="plusOne();">+1</button>
<button onclick="minusOne();">-1</button>
<p id="number">0</p>

<button id="enableMe">Enabled when 10 or over</button>

Thanks in advance!

Advertisement

Answer

Simply make an update function on click. No need to continuously run a function a thousand times per second. Also start with your button disabled (since the counter starts at 0).

var numberCounter = 0;
var number = document.getElementById("number");

function plusOne() {
  numberCounter++;
  number.innerHTML = numberCounter;
  updateButton();
}

function minusOne() {
  numberCounter--;
  number.innerHTML = numberCounter;
  updateButton();
}

function updateButton() {
  enableMe.disabled = (+number.innerHTML < 10)
}
<button onclick="plusOne();">+1</button>
<button onclick="minusOne();">-1</button>
<p id="number">0</p>

<button id="enableMe" disabled>Enabled when 10 or over</button>

Actually, by optimizing a little, it can even be a one-liner!

const change = amount => enableMe.disabled = (number.innerHTML = +number.innerHTML + amount) < 10;
<button onclick="change(1)">+1</button>
<button onclick="change(-1)">-1</button>
<p id="number">0</p>

<button id="enableMe" disabled>Enabled when 10 or over</button>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement