Javascript变量可见性

时间:2015-01-29 10:15:59

标签: javascript variables global-variables scope

我是javascript世界的新手。阅读有关变量范围的内容,我认为我有了这个想法。我做了一些实验,我在这里遇到了一些情况,这给了我意想不到的结果。这就是我的意思

var x = 0;

function set(){
  x++;
}

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

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

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

在脚本的这一点上,total的值总是为0.我已经检查过了,我确定total的值是增加的。那么第二个例子的错误是什么以及为什么全局变量total的值没有改变呢?

2 个答案:

答案 0 :(得分:0)

您正在使用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);

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

答案 1 :(得分:0)

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

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

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