[英]Can't update global variables in javascript
似乎找不到答案。 我无法使用函数更改变量,也无法在函数外部与之交互。 这是我的代码:
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;
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上测试
演示
尝试:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.