lassehas
lassehas

Reputation: 85

Checkbox when unchecked

Im trying to make a checkbox do a timing event when it's checked, and stops when unchecked. It works when checked, but when I uncheck it, it just do the function again, the variable just getting higher faster.

Live

JS Code

var money = 0;

function moneyMaker(){
    money++;
  document.getElementById('money').innerHTML = money;
}

function doautoMoney(){
    window.setInterval(function(){

        moneyMaker();
        document.form.automoney.click();
        //alert('Auto Saved!');
    }, 1000); 
}

Upvotes: 0

Views: 49

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115282

Clear the interval on unchecked using clearInterval() and instead of onclick use onchange in case of checkbox.

var money = 0;

function moneyMaker() {
  money++;
  document.getElementById('money').innerHTML = money;
}
var int;

function doautoMoney(chk) {
  if (chk)
    // store the interval reference for clearing the interval
    int = window.setInterval(function() {
      moneyMaker();
      //document.form.automoney.click();
      //alert('Auto Saved!');
    }, 1000);
  else
    clearInterval(int)
}
Money: <span id="money">0</span>
<p>
  <button onclick="moneyMaker(1)">Mine Iron!</button>
  <input type="checkbox" name="automoney" onchange="doautoMoney(this.checked);">

Upvotes: 2

Related Questions