如何调查为什么setTimeout函数在我的代码中不起作用?

时间:2019-04-25 21:33:48

标签: javascript blockly

我的代码有效,并且所有值都正确,因此应该可以运行,但是不能运行。

我尝试过对变量进行本地化,更改时间以及重新排列功能和名称标签。

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");
      }
    });
}

我希望它每1000毫秒为我的money变量加1。但这对货币变量没有任何作用

4 个答案:

答案 0 :(得分:2)

这里有一些问题:

setTimeout仅在1000毫秒结束时运行一次。在这种情况下,当它运行时,您将进入一个无限循环,因为autotrue永远不会设置为true。它仍然是0,并且您将其添加到金钱中,金钱永远不会超过10,因为0 + 0 = 0。

如果您想每1000毫秒重复增加一次收益,则可以使用setInterval,而不会产生任何循环。每隔1000毫秒就会调用一次函数。

答案 1 :(得分:0)

您在变量autocountautotrue初始化为0之前调用undefined,因此它们仍然是while(autotrue==1){,将破坏您的计算。您应该在初始化所有变量后调用 函数。

另外,autotrue看起来像是无限的,因为{{1}}没有任何变化。无限循环总是不好的。

答案 2 :(得分:0)

进行此操作,您将看到计时器起作用。

  while(autotrue==1){
    money = money + autocount;
    setText("money_display",money);

您的问题是您没有在任何地方将autotrue var设置为1。

答案 3 :(得分:0)

您的代码有几个问题:

  1. money变量未定义
  2. 计时器中的while循环会使浏览器冻结
  3. timeout应该是interval
  4. autotrue应该是布尔值

为了工作示例,我伪造了setText()函数并将onEvent()更改为addEventListener()

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>