It runs all the time after a second instead of going one by one, and I would like to know how to fix it so that it works correctly
Code:
for (let i = 0; i < tierra.length; i++) {
setTimeout(() => {
gameScene.addChild(tierra[i]);
}, 1000);
}
Your question is more about logic, how does it work, there is a trick for this; and is to add the seconds that corresponds to wait:
I put the example for practical purposes:
What you want to do can also be done by promises but it will depend on the above logic; For now, this way is simple and practical.
With promises it would be better because it would effectively wait 1 second after executing the first instruction ( Francisco Romero variation )
If what you want is for each iteration of the loop to be executed with a time interval of one second between executions, you could create a function that calls itself with an interval of 1 second using the function
setTimeout
.Example:
where 5 would be the number of iterations,
tierra.length
in your case.In case you wanted an infinite loop that repeated every second you could use the
setInterval
.Example: