Use requestAnimationFrame
(rAF) instead. The 20ms makes no sense. Most video runs at 30 FPS in the US (NTSC system) and at 25 FPS in Europe (PAL system). That would be 33.3ms and 40ms respectively.
That being said, rAF will attemp to run at 60 FPS (or the monitor refresh rate up to 60 Hz) so we can reduce the frame rate here by using a toggle switch.
In any case rAF will enable the drawing to be synced to the monitor so in any case it will be a better choice than setInterval
/setTimeout
in cases such as these.
The reason you get a crash is probably due to stacking taking place (but it could also be system related).
var toggle = true;
function loop() {
toggle = !toggle;
if (toggle) {
if (!v.paused) requestAnimationFrame(loop);
return;
}
/// draw video frame every 1/30 frame
ctx.drawImage(v, 0, 0);
/// loop if video is playing
if (!v.paused) requestAnimationFrame(loop);
}
Then use this simplified version of that example:
var v = document.getElementById("video1");
var c = document.getElementById("myCanvas");
var ctx = c.getContext('2d');
v.addEventListener('play', loop ,false);