似乎找不到答案。我不能用我的函数更改变量并在函数外部与它交互。这是我的代码:
var secondsLeft = 10;
function deathCounter() {
secondsLeft
if(secondsLeft > 0) {
secondsLeft--;
$('#deathCounter').text(secondsLeft);
setTimeout(deathCounter, 1000);
console.log('inside function: ' + secondsLeft)
}
}
console.log('outside function: ' + secondsLeft);
它目前只更新外部函数一次,然后在函数内部每秒更新一次。但是我也不想在功能之外更新。我该怎么做?
演示
尝试:
var secondsLeft = 10;
function deathCounter() {
if(secondsLeft>0) {
secondsLeft-- ; // note the -- here!
$('#deathCounter').text(secondsLeft); // Now text will update correctly
console.log('inside function: ' + secondsLeft); // and the log
setTimeout(deathCounter, 1000);
}
}
console.log('outside function: ' + secondsLeft);
deathCounter();
试试这个:
var secondsLeft = 10;
setTimeout(deathCounter, 1000);
function deathCounter() {
if(secondsLeft > 0) {
secondsLeft--;
$('#deathCounter').text(secondsLeft);
setTimeout(deathCounter, 1000);
console.log('inside function: ' + secondsLeft);
}
}
console.log('outside function: ' + secondsLeft);
您从未在函数外部调用函数。在 jsbin 上测试