Ghoyos Ghoyos - 4 months ago 11
HTML Question

JS AnimationEnd Loop, would like to loop continually WITHOUT using; setInterval/setTimout

In the below code I am trying to loop three functions that only fire once the previous function is complete, with the last function then calling the first to start the process all over again. Using setInterval/setTimout are not going to be good answers for this because of RequestAnimationFrame taking their place as a cleaner way of doing things but I dont know how to apply RequestAnimationFrame to this code. Also the question of why the third function does not call the first wouldn't be answered by using those two methods as well.

<body onload="runOne()">

function runOne(){
var x = document.getElementById("rightBox");
document.getElementById("rightBox").style.animation = "scrollTextTwo 10s";
x.addEventListener("animationend",runTwo);
};


function runTwo(){
var x = document.getElementById("rightBoxTwo");
document.getElementById("rightBoxTwo").style.animation = "scrollTextTwo 10s";
x.addEventListener("animationend",runThree);
};


function runThree(){
var x = document.getElementById("rightBoxThree");
document.getElementById("rightBoxThree").style.animation =
"scrollTextTwo 10s";
x.addEventListener("animationend",runOne);
};


The above code works only once, it will play/animate all three functions but then stops after "runThree()" is complete. I would like to know how "runThree()" can call "runOne()" once run three is completed with its animation?

Answer

So, I think you have several options: What could work is that you reset the the animation of rightBox in function runTwo with animation: none. If you assign scrollTextTwo 10s back to the rightBox it should start again. Equivalent for the other ones.

See the following Codepen, where I implemented an endless CSS animation using JavaScript.

Alternatively it's also possible to do it without JavaScript: You can use animation-delay, infinite repeating and some other tricks to create really complex animation timelines, maybe also take a look at the following question.