I'm building an application that makes a user-specified number of calls to canvas.putImageData
in Javascript. Between each call to putImageData
, the image data is modified. The time needed to modify the data varies between calls. The user also needs to be able to stop the animation while it's running (I'm using a button). Initially I used:
for (var i=0; i < n; i++) {
canvas.putImageData(imgdata, 0, 0);
modify(imgdata);
}
However, this doesn't display each frame, only the last one. What does work is to put an alert after canvas.putImageData
, but that's super annoying. I tried using setInterval
and cancelInterval
as I'm sure many would suggest, but this doesn't work for me for two reasons:
- The time needed to modify the image data varies.
- setInterval is asynchronous; if the delay I use is too short, calls to modify(imgdata) pile up on the stack and users won't be able to stop the animation when they want.
How can I make this work correctly?
Use a repeating setTimeout():
This will display and modify the image data each second.
Another solution would be to delegate the modify algorithm to a web worker.