I've got a code that will run a set of 20 images, to make it look like an idle sprite is breathing when idle. This runs perfect when its only one loop.
However I can't get it to repeat that loop indefinitely.
Is there a cleaner and faster way to do what i'm doing?
Enclosing that in another for loop doesn't work. It ends in it never loading.
for(let i = 0; i < images.length; i++) {
window.setTimeout(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(images[i], 100, 100);
}, 100 * i);
}
Run Code Online (Sandbox Code Playgroud)
I expect it to keep looping indefinitely.
Que*_*tin 10
摆脱for循环,使用间隔(管理“每个时间做某事”的标准方法),并管理i回调内部的值。
let i = 0;
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(images[i], 100, 100);
i++;
if (i === images.length) i = 0;
}, 100);
Run Code Online (Sandbox Code Playgroud)