setTimeout with Loop in JavaScript -


i have trivial question. simple loop settimeout, this:

for (var count = 0; count < 3; count++) {     settimeout(function() {         alert("count = " + count);     }, 1000 * count); } 

console gives output this:

count = 3 count = 3 count = 3 

not sure why output this. explain, please?

this has how scoping , hoisting being treated in javascript.

what happens in code js engine modifies code this:

var count;  (count = 0; count < 3; count++) {     settimeout(function() {         alert("count = " + count);     }, 1000 * count); } 

and when settimeout() being run first in it's own scope after count won't find it'll start looking in functions closes (this called closures) on settimeout function until finds var count statement, have value 3 since loop have finished before first timeout function has been executed.

more code-ily explained code looks this:

//first iteration var count = 0; //this 1 because of count++ in loop.  (count = 0; count < 3; count++) {      settimeout(function() {         alert("count = " + 1);     }, 1000 * 1); } count = count + 1; //count = 1  //second iteration var count = 1;  (count = 0; count < 3; count++) {     settimeout(function() {         alert("count = " + 2);     }, 1000 * 2); } count = count + 1; //count = 2  //third iteration var count = 2;  (count = 0; count < 3; count++) {     settimeout(function() {         alert("count = " + 3);     }, 1000 * 3); } count = count + 1; //count = 3  //after 1000 ms window.settimeout(alert(count)); //after 2000 ms window.settimeout(alert(count)); //after 3000 ms window.settimeout(alert(count)); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -