Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading