Search code examples
javascriptblockly

How to investigate why the setTimeout function is not working in my code?


My code works and all values are true so that it should be running, but it does not.

I have tried localizing the variables, changing the timing, and rearranging functions and nametags.

auto1();  
var autocount = 0;
var autotrue = 0;

function auto1(){
    setTimeout(function() {
      while(autotrue==1){
        money = money + autocount;
        setText("money_display",money);
      }
    }, 1000);

    onEvent("auto1", "click", function(){
      if(money >= 10){autotrue = 1;
        money = money - 10;
        autocount = autocount+1;
        console.log("You now have " + autocount + " J$ per second");
      } else {
        console.log("you have insufficient J$ for this purchase");
      }
    });
}

I expect it to add 1 to my money variable every 1000 ms. But it does nothing to the money variable


Solution

  • There were several issues with your code:

    1. the money variable was not defined
    2. The while loop inside the timer would make the browser freeze
    3. the timeout should be an interval instead
    4. autotrue should probably be a boolean

    I faked the setText() function and changed onEvent() to addEventListener() for the sake of a working example:

    auto1();
    
    var autocount = 0;
    var autotrue = false;
    var money = 10;
    
    function auto1() {
      autoAddInterval = setInterval(function() {
        if (autotrue) {
          money = money + autocount;
          setText("money_display", money);
        }
      }, 1000);
      document.getElementById('auto1').addEventListener("click", function() {
        if (money >= 10) {
          autotrue = true;
          money = money - 10;
          autocount = autocount + 1;
          console.log("You now have " + autocount + " J$ per second");
        } else {
          console.log("you have insufficient J$ for this purchase");
        }
      });
    }
    
    function setText(id, value) {
      document.getElementById(id).innerText = value + ' J$';
    }
    
    setText("money_display", money);
    balance: <span id="money_display">0 J$</span><br>
    <button id="auto1">purchase +1 J$ per second</button>