无法在javascript中更新全局变量

时间:2014-02-27 17:41:33

标签: javascript jquery function global-variables

似乎无法找到答案。我无法使用我的函数更改变量并在函数外部与其进行交互。这是我的代码:

    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);

它目前只更新外部函数一次,然后每秒更新一次函数。但我也不想在功能之外更新。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

试试这个:

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

上测试过

答案 1 :(得分:0)

DEMO
试试:

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();