Click here to Skip to main content
14,692,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a big problem; two code snippet below
without SetTIMEOUT

for(var i=1;i<=2;i++  )
              (function (){
                  console.log(i);
              })() ;

output(completely understand able for me)
1
2

withsetTime out
for(var i=1;i<=2;i++  )
              setTimeout(function (){
                  console.log(i);
              }) ;

it returning me [quite confusing for me]
3
3

i know that setTimeout repeat a function\work within some duration but the above code i am not getting why this is returning 3 and 3?? how does it works?
Posted

What is there to be confused about think about it carefully.

=> setTimeout() - executes a function, once, after waiting a specified number of milliseconds

You loop it thru the inside function twice ... How long do you think that will take?????

The answer is very very very very fast like less than 1 millisecond

So by the time the delayed functions ever run i will be 3 ... the bailout condition of your loop

here it is step by step

step 1: i = 1 it launchs the first SetTimeout (very very fast < 1 millisecond)
step 2: i is incremented so i now = 2 
step 3: i = 2 it launchs the second SetTimeout (very very fast < 1 millisecond)
step 4: i is incremented so i now = 3
step 5: the loop bails out because i fails the condition i<=2

** AT THIS POINT =>     i = 3

Some time later 1st SetTimeout function runs ... correctly returning that i = 3
Some time later 2nd Setimeout function runs ... correctly return that i = 3
   
v2
Comments
Muhamad Faizan Khan 8-Mar-14 0:17am
   
it means loop runs faster then the time we do define in setTimeout. Time doesn make differece?
You should read this to understand JavaScript closures vs. anonymous functions[^]
Run the following example to see the result:
<!DOCTYPE html>
<html>
<body>
<button onclick="testing()">Try it</button>
<script>
function testing()
{
    for(var i=1;i<=2;i++){



       document.write("before i = " + i + "<br>");

       setTimeout(
          (function(s){document.write("setTimeout function = " + s + "<br>");})(i)
       );

       document.write("after i = " + i + "<br>");
    }
}
</script>
</body>
</html>

The outcome is:
before i = 1
setTimeout function = 1
after i = 1
before i = 2
setTimeout function = 2
after i = 2
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900