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/