2

I'm new in javascript world. Reading about the variables scope and I think I got the idea behind. I did some experiments and I'm having a situation here which gives me unexpected results. Here's what I mean

var x = 0;

function set(){
  x++;
}

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

At this point of the script the value of x is 1 as expected

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

At this point of the script the value of total is always 0. I've checked and I'm sure the value of total is incremenated. So what's wrong with the second example and why the value of global variable total is not changed?

Vodokan
  • 723
  • 1
  • 8
  • 16
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Qantas 94 Heavy Jan 29 '15 at 10:54

2 Answers2

0

You are using setInterval, which creates an interval after which the the function(passed as argument to the setInterval function) is executed periodically,

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

So, here-

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

You can try this

total = 0;

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

in this case the total is printed after it is been incremented

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
0

Its because java script is asynchronous. console.log will be executed first and thereafter the function inside setInterval will be executed as it has been given 10 millisecond of delay...

To see the incremented value of 'total', you can run the below given code just after the setInterval.

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