如何声明此变量

时间:2019-04-23 16:39:19

标签: javascript app-lab

我正在使用App Lab(code.org)开发一个应用程序。很抱歉,如果这是一个非常简单的解决方法。我3个月前才开始使用javascript,这是我的第一个项目。

我希望他们一旦点击按钮“ start_city_game_button”就开始倒计时,但是我遇到了这个错误

setInterval() callback parameter value (1000) is not a function

setInterval() milisecond parameter value (undefined) is not a number.

这些错误出现在第2行中。

var city_time = 60;
var city_time_counter = setInterval(1000);

function cityTimer() {
city_time = city_time -1;
  clearInterval(city_time_counter);
  }
}

我希望计时器一旦启动关卡便会启动,但是实际上该时间是在应用启动时开始的。我遍历了这段代码的许多草稿以找到正确的答案,但我找不到办法。

onEvent("back_mainscreen", "click", function() {
  setScreen("start_screen");
});
onEvent("instructions", "click", function() {
  setScreen("instructions");
});
onEvent("startgame", "click", function() {
  setScreen("city_screen");
});

// City Code
var city_tries = 0;
var city_time = 60;
var city_time_counter = setInterval(1000);



onEvent("start_game_city_button", "click",function() {
city_time = city_time -1;
console.log(city_time);
setText("second_city_time", city_time);
  if (city_time === 0) {
  setScreen("city_screen");
  clearInterval(city_time_counter);
  }
});
  
  onEvent("start_game_city_button", "click", function() {
  console.log("CONSOLE: Player Started City Level");
  console.log(city_tries);
  setScreen("city_game_screen");
  city_tries = city_tries + 1;
});




var score = 0;
onEvent("deer", "click", function() {
  setPosition("deer", randomNumber(50,240), randomNumber(50, 400));
  score = score + 1;
 setText("score_label", score);
});
// Ocean Code
var ocean_tries = 0;
onEvent("ocean_start_button", "click", function() {
    ocean_tries = ocean_tries + 1;
  console.log("CONSOLE: Player Started Ocean Level. Try");
    console.log(ocean_tries);
});

1 个答案:

答案 0 :(得分:2)

setInterval的第一个参数是一个函数。第二个参数是时间量。

var city_time_counter = setInterval(cityTimer,1000);

如果您希望定时器在单击时启动,然后将侦听器附加到元素并在其中设置setInterval。

document.getElementById("start_city_game_button").addEventListener('click',()=>{
    city_time_counter = setInterval(1000);
})

此外,如果您需要将变量减少1,可以为此使用简写方式。

city_time = city_time -1;

上面的行与

相同
city_time--;