【问题标题】:Javascript variable visibilityJavascript变量可见性
【发布时间】:2015-01-29 10:15:58
【问题描述】:

我是 javascript 世界的新手。阅读变量范围,我想我明白了背后的想法。我做了一些实验,我在这里遇到了一种情况,这给了我意想不到的结果。这就是我的意思

var x = 0;

function set(){
  x++;
}

set();
console.log(x) // 1

在脚本的这一点上,x 的值是预期的 1

total = 0;
var id = setInterval(function(){
 total++; 
}, 10);
console.log(total); // 0

在脚本的这一点上,total 的值始终为 0。我已经检查过,我确定 total 的值是递增的。那么第二个例子有什么问题,为什么全局变量total的值没有改变呢?

【问题讨论】:

标签: javascript variables global-variables scope


【解决方案1】:

您正在使用 setInterval,它会创建一个间隔之后,该函数(作为参数传递给 setInterval 函数)定期执行,

阅读https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval

所以,这里-

total = 0;
var id = setInterval(function(){
 total++; 
}, 10);
console.log(total); // 0

 console.log(total); is executed before then the function inside the `setInterval` executes(aftyer a delay of 10ms).

你可以试试这个

total = 0;

    var id = setInterval(function(){
     total++; 
     console.log(total);
    }, 10);

在这种情况下,总数是在递增后打印的

【讨论】:

    【解决方案2】:

    这是因为 java 脚本是异步的。 console.log 将首先执行,然后 setInterval 中的函数将被执行,因为它被赋予了 10 毫秒的延迟......

    要查看 'total' 的增量值,您可以在 setInterval 之后运行以下给出的代码。

     window.setTimeout(function(){
         console.log(total);
        }, 10);
    

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 2015-07-06
      • 2017-06-13
      • 1970-01-01
      • 2015-10-20
      • 2014-09-20
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多