I want to show an ongoing number with JavaScript.
For this I have developed the following example:
for(var i=0; i<100; i++) {
window.setTimeout(function() {
alert(i);
},1000*i);
}
Unfortunately the number 100 is shown every time. I think it is because i is a reference?
How can this be changed in the parameter passing?
The problem is that JS does not wait and proceeds finishing the loop before the timeouts expire. By then,
iis already 100.To work around this issue, your timeout should have a local reference of
i. That way, it’s not referencing theithat is already 100 by then, but referencesiat that time of the loop.