I have an example on this code:
<script>
for(var i=1; i<3; i++){
setTimeout(function(){
say("HELLO NUMBER " + i);
}, i * 2000);
}
function say(text){
alert(text);
}
</script>
And output I need is :
alert("HELLO NUMBER 1");
alert("HELLO NUMBER 2");
But in this case, I still get output :
alert("HELLO NUMBER 3");
Anyone can help for this? thanks :)
-
1Possible duplicate: stackoverflow.com/questions/10954053/…go-oleg– go-oleg2013年07月10日 05:23:54 +00:00Commented Jul 10, 2013 at 5:23
-
its about query search... but thanks for your suqestionRaindy Saha– Raindy Saha2013年07月11日 10:43:18 +00:00Commented Jul 11, 2013 at 10:43
4 Answers 4
Classic problem with closure
for(var i=1; i<=3; i++){
(function(num){
setTimeout(function(){
say("HELLO NUMBER " + num);
}, num * 2000);
})(i)
}
function say(text){
alert(text);
}
Demo: Fiddle
You are using a closure variable i inside the setTimeout callback, whose value is evaluated only when the callback is executed by then the value of i will be updated by the outside loop
answered Jul 10, 2013 at 5:23
Arun P Johny
389k68 gold badges533 silver badges532 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Another way.
var out = [];
for(var i=0; i<3; ++i){
out.push(i+1);
setTimeout(function(){
say("HELLO NUMBER " + out.shift());
}, i * 2000);
}
function say(text){
alert(text);
}
Comments
you need a closure for the value of i for each iteration:
for (var i=1; i<3; i++) {
(function(j){
setTimeout(function() { alert("HELLO NUMBER " + j); }, j*2000);
})(i)
}
answered Jul 10, 2013 at 6:02
Francisco Meza
8836 silver badges8 bronze badges
Comments
<script>
function doSetTimeout(i) {
setTimeout(function() { say("HELLO NUMBER " + i); }, 3000);
}
for(var i=1; i<3; i++){
doSetTimeout(i);
}
function say(text){
alert(text);
}
</script>
answered Jul 10, 2013 at 6:03
Kousik
22.6k7 gold badges39 silver badges60 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js