[英]Simple JavaScript, cant get my head around it
x = 1;
var add = function (x) {
x++;
return x;
};
setTimeout(add, 1000);
console.log(x);
Why is this not working properly? 为什么这不能正常工作? Console only says 1 and stops, but I want it the addition of x every time the add handler is called with the timeout property (1 2 3 4 and soforth).
控制台只说1并停止,但是我希望每次使用timeout属性(1 2 3 4等)调用添加处理程序时都将x加法。 I know I can just use a for loop for this.
我知道我可以为此使用for循环。 But I'd like to know if it could be done this way also.
但是我想知道是否也可以这样进行。
setTimeout
is asynchronous. setTimeout
是异步的。 You tell it to execute add
1 second (1000 milliseconds) later, and it does. 您告诉它在以后执行
add
1秒(1000毫秒),然后执行。 In the meantime, console.log(x)
is executed, and logs the current value of x
, 1. 同时,执行
console.log(x)
并记录x
的当前值1。
In the question you say you want to see the value constantly incrementing. 在问题中,您说您希望看到该值不断增加。 For that, you need to use code more like this:
为此,您需要使用如下代码:
var x = 1;
function add() {
x++;
console.log(x);
};
setInterval(add, 1000);
EDIT: Also, look at Quentin's bullet point 2 about masking the global variable. 编辑:另外,请参阅有关隐藏全局变量的昆汀的要点2。
console.log
at the start. console.log
。 Move it inside the function so it runs every time the function does. x
, this masks the global one. x
拥有一个(从未填充过的)参数,这将掩盖全局变量。 Remove it. Such: 这样:
var x = 1;
function add() {
x++;
console.log(x);
};
setTimeout(add, 1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.