skip to Main Content

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

2

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. You can create a helper function:

    async function sleep(ms) { 
      return new Promise(resolve => setTimeout(resolve, ms)); 
    }
    

    and make your function async, and use await, like this:

    await sleep(1000); // 1 second
    

    Another thing, the getElementsByClassName returns a html collection.

    your refactored function:

    async function videoplayer (frameamt) {
        var frameamount = frameamt + 1
        var frame = 1
        var video = document.getElementsByClassName("vidplyr")[0]; // <- Add the [0]
        while (frame < frameamount) {
            var frame = frame + 1
            video.src = frame + ".png"
            
            await sleep(50); // <- Add this
        }
        if (frame > frameamount) {
            video.src = "1.png"
        }
    }
    

    UPDATE


    I have just seen Lukas’s answer.
    While my answer provides a strait forward solution for including sleeping in a loop, his answer is more suitable, and you should use it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search