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
What you are looking for is
setInterval()
and not awhile
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:
You can create a helper function:
and make your function async, and use await, like this:
Another thing, the
getElementsByClassName
returns a html collection.your refactored function:
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.