Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a while loop that executes every 50 miliseconds

I made that javascript script

function videoplayer (frameamt) {
    var frameamount = frameamt + 1
    var frame = 1
    var video = document.getElementsByClassName("vidplyr");
    while (frame < frameamount) {
        var frame = frame + 1
        video.src = frame + ".png"
    }
    if (frame > frameamount) {
        video.src = "1.png"
    }
}

But I want to make the while loop execute every 50 miliseconds if the condition matches

I want to make a video player that is based in images that represent frames and is 20 fps
meaning that i need to execute every 50 miliseconds to change the image

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you are looking for is setInterval() and not a while loop (or any other loop). Letting the main thread wait (inside a loop) in JavaScript is undesirable because you would have to let the cpu do something useless in order to waste time.

This could be a starting point:

function videoplayer (frameamt) {
    var frameamount = frameamt + 1;
    var frame = 0; // if this is 1 here you only start at frame 2
    var video = document.getElementsByClassName("vidplyr")[0]; // you need [0] here to take the first match
    var interval = setInterval(function () {
        frame = frame + 1;
        video.src = frame + ".png";
        // condition to cancel the interval
        if (frame >= frameamount) {
            clearInterval(interval);
        }
    }, 50) // execute every 50 ms
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading