Reputation: 63
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). I know I can just use a for loop for this. But I'd like to know if it could be done this way also.
Upvotes: 1
Views: 127
Reputation: 943579
console.log
at the start. Move it inside the function so it runs every time the function does.x
, this masks the global one. Remove it.Such:
var x = 1;
function add() {
x++;
console.log(x);
};
setTimeout(add, 1000);
Upvotes: 2
Reputation: 35803
setTimeout
is asynchronous. You tell it to execute add
1 second (1000 milliseconds) later, and it does. In the meantime, console.log(x)
is executed, and logs the current value of 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.
Upvotes: 4