javascript - 当 setInterval() 运行另一个函数时,一个有效的函数突然变为 "not a function"

标签 javascript function setinterval

tl;dr:当我让 setInterval() 每 3 秒运行另一个函数时,我的函数不会运行。

我正在制作一个基于文本的园艺游戏,当我输入 plant 时,该游戏会运行“plant()”。我还进行了 setInterval(updatePlots, 3000) 操作。

这两个函数本身都可以正常工作,但是当我尝试在 setInterval() 运行时运行 plant() 时,会出现错误 Uncaught TypeError: plant is not a function

(我知道这是 setInterval(),因为我在没有运行它的情况下测试了种植,并且效果很好。)

我尝试过的(没用):

if (command == "plant") {
  clearInterval(timer);
  plant(a, b);
  var timer = setInterval(updatePlots, 3000);
}
<小时/>

我不太确定我要显示什么代码,因为它似乎比单行错误更根本的问题......但它就是这样。

function updatePlots() {
  fullplots = [];
  for (i = 0; i < plots.length; i++) {
    if (plots[i].length) {
      fullplots.push(i);
    }
  }

  for (i = 0; i < fullplots.length; i++) {
    plant = plots[fullplots[i]][0];
    status = plots[fullplots[i]][1];
    growth = plots[fullplots[i]][2];

    if (growth < 100) {
        plots[fullplots[i]][2]++;
    }
  }

  if (document.getElementById('plots').style.display == 'block') {
    getPlots();
  }
}

...

function processTwo(command, a) {
  if (command == 'plant') {
    clearInterval(timer);
    console.log('about to plant 1'+a);
    plant(1, a);
    var timer = setInterval(updatePlots, 3000);
  }
  else { createError() }
}

更新:已解决!

最佳答案

function updatePlots() {
  // this way, the global plant function is not overwritten
  // @see JavaScript variable scope
  var plant;
  // You might want to 'var' your other local (?) variables, too
  // var fullplots, i, status, growth;
  fullplots = [];
  for (i = 0; i < plots.length; i++) { //get fullplots
    if (plots[i].length) {
      fullplots.push(i);
    }
  }

  for (i = 0; i < fullplots.length; i++) {
    // at this line of code you overwrite the global plant, which is not a function anymore then
    plant = plots[fullplots[i]][0];
    status = plots[fullplots[i]][1];
    growth = plots[fullplots[i]][2];

    if (growth < 100) { //increment
        plots[fullplots[i]][2]++;
    }
  }

  if (document.getElementById('plots').style.display == 'block') {
    getPlots();
  }
}

关于javascript - 当 setInterval() 运行另一个函数时,一个有效的函数突然变为 "not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249981/

相关文章:

javascript - 从 javascript 调用 Asp Action

javascript - 跟踪器计算在生产中不起作用

Javascript - 通用函数的多种使用

javascript - 如何将 setInterval 和 .on ("click") 函数连接在一起?

javascript - 在 JavaScript 中同时多次调用具有相同构造函数的对象内的 setInterval

javascript - onSelect事件datepicker触发timepicker中minTime值的变化

javascript - 如何从数组中取出数组并将其分配给另一个数组

c++ - C++调用非虚成员函数的机制是什么?

javascript - 如何让greasemonkey运行特定的javascript : function?

javascript - 如何在 Canvas 上制作弹跳球的动画