javascript var declaration within loop

Posted by Trouts on Stack Overflow See other posts from Stack Overflow or by Trouts
Published on 2010-04-28T15:58:39Z Indexed on 2010/04/28 16:03 UTC
Read the original article Hit count: 144

Filed under:

hello,

/*Test scope problem*/
for(var i=1; i<3; i++){
    //declare variables
    var no = i;
    //verify no
    alert('setting '+no);

    //timeout to recheck 
    setTimeout(function(){
        alert('test '+no);
    }, 500);
}

it alerts "setting 1" and "setting 2" as expected, but after the timeout it outputs "test 2" twice - for some reason the variable "no" is not reset after the first loop...

i've found only an "ugly" workaround...

/*Test scope problem*/
var func=function(no){
    //verify no
    alert('setting '+no);

    //timeout to recheck 
    setTimeout(function(){
        alert('test '+no);
    }, 500);
}
for(var i=1; i<3; i++){
    func(i);
}

Any ideas on how to workaround this problem in a more direct way? or is this the only way?

© Stack Overflow or respective owner

Related posts about JavaScript