Problem
I know to pass a parameter to a setTimeout function you would use javascript’s “closure” to get it to work:
setTimeout(function(){alert(someParameter)}, 1000);
However if you are setting someParameter in a loop, setTimeout will always alert the last value set to someParameter.
Solution
The solution is to set a scope around setTimeout like so:
var strings = [ "hello", "world" ]; var delay = 1000; for(var i=0;i<strings.length;i++) { (function(s){ setTimeout( function(){alert(s);}, delay); })(strings[i]); delay += 1000; }
source: http://stackoverflow.com/questions/6425062/passing-functions-to-settimeout-in-a-loop-always-the-last-value