An introduction to JavaScript Framework “Angular”

AngularJS is a javascript library similar to jquery where you don’t need to code like javascript or jquery, just play with attributes and save the time of coding. Angular JS is also called Javascript Framework i.e. MVW- Model View Whatever – framework.

 No need of coding for arithmetic calculation, just play with angular expression:

 <p>Sum of 5 and 5: {{ 5 + 5 }}</p> will produce Sum of 5 and 5: 10

Try the same with Angular Bind, you’ll get the same result, but there are some differences of syntax and others. 

JQuery setTimeout inside for loop

Today I was amazed with a question asked by one of my IT friends. 

What’ll be the output of setTimeout function if I declare it inside the for loop like this.

 

  1. for(i=0;i<3;i++)
  2. {
  3.     console.log(i);
  4. }
  5.  

 

My answer was 

 

  1. 0
  2. 1
  3. 2
  4.  

 

But the answer was not correct as he challenged and I checked it too. The answer was ‘2’ only.

 

I tried to know why the output is so. I thought that this is because of threading it’ll be skipping the setTimeout function some time due to thread concept. But when I changed the condition to i<10000, but the output was same. Finally I’s not able to know the situation and problem.

 

At last I searched on forems, and I got my answer which is as follows:

The function argument to setTimeout is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i, which is 4.

Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:

 

  1. for (var i = 0; i < 3; i++) {
  2. (function (x) {
  3. setTimeout(function () { alert(x); }, 100);
  4. })(i);
  5. }

 

You might also check this Q/A on stackoverflow