Humans start perceiving time intervals somewhere between a 20th and a 10th of a second, so trying to poll with a value of 1ms is neither necessary nor desireable (any modern browser will round that up to 5ms or 10ms anyway). Values like 50 or 100 would be more appropriate.
I would also strongly recommend using a chained series of setTimeout
calls rather than a setInterval
call, something like this:
function onVideoReady(callback) {
// Do first check as soon as the JavaScript engine is available to do it
setTimeout(checkVideoReady, 0);
// Our check function
function checkVideoReady() {
if (videoIsReady) {
// The video is ready, notify calling code
callback();
}
else {
// Not ready yet, wait a 10th of a second
setTimeout(checkVideoReady, 100);
}
}
}
...which you then use like this:
onVideoReady(function() {
// The video is ready, do something
});
The reasons I advocate a chained series of setTimeout
instead of setInterval
are:
You can change the delay easily from iteration to iteration. For instance in the above, I fire the check as soon as possible the first time, then then after 100ms each subsequent time. You can do more complex things with timing than that, the flexibility is there.
It's much, much harder to inadvertently end up with more than one running, since code has to explicitly trigger the next loop.
setInterval
varies amongst browsers about whether it measure the interface from the start of the last call or the end of it. If you use a pattern like the above, you're always sure it's from the end of the last check.
If your code is still running when the next interval is meant to occur, it just gets skipped. This can cause gaps (e.g., if you're doing something every 100ms and your previous loop takes 102ms to complete, the next one doesn't start as soon as possible, it waits the remaining 98ms), at least on some browsers.
But it's up to you, of course, the above can be done just as easily with setInterval
and clearInterval
calls as with a chain of setTimeout
calls.