javascript - setTimeout is not working correctly inside "for loop" -
now of course, code make do.
but i'm confused why in following code:
var = { 0: "hi", 1: "bye" } (var b in a) { settimeout(function () { console.log(b); }, 1000); }
instead of consoling "0" , "1"
i "1" twice.
i'm not sure why happens. need setup script making same issue.
it because usage of closure wrong.
in case using closure variable b
inside settimeout
callback, value of variable b
not looked until callback executed, value of updated last value in object.
one of solution in such case create local closure given below
for (var b in a) { (function(c){ settimeout(function () { console.log(c); }, 1000); })(b) }
demo: fiddle
Comments
Post a Comment