People begin to perceive time intervals somewhere between 20 and 10 seconds, so trying to interrogate with a value of 1ms is neither necessary nor desirable (any modern browser will round up to 5 ms or 10 ms in any case). Values such as 50 or 100 would be more appropriate.
I also highly recommend using the setTimeout chaining chain rather than calling setInterval , 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 as follows:
onVideoReady(function() {
The reasons I protect the setTimeout chain instead of setInterval are as follows:
You can easily change the delay from iteration to iteration. For example, in the above example, I start the check as soon as possible for the first time, and then after 100 ms every subsequent time. You can do more complex things with time than flexibility.
This is much more difficult than unpredictable; it ends with more than one run, as the code must explicitly run the next loop.
setInterval varies among browsers about whether it measures an interface from the beginning of the last call or its end. If you use a template like the one above, you are always sure of it from the end of the last check.
If your code is still running when the next interval should happen, it is simply skipped. This can lead to spaces (for example, if you do something every 100 ms and your previous cycle takes 102ms to finish, the next one does not start as soon as possible, it waits for the remaining 98ms), at least in some browsers.
But to you, of course, the above can be done as easily with setInterval and clearInterval calls as with setTimeout chaining.
source share