Search code examples
javascriptloopstimerequestanimationframe

How to make the animation run every x seconds


I want an animator that if I have like this

index = 0;
function animate() {
    index++;
    requestAnimationFrame(animate);
}

But how do I make it so index++ is every x second? so if x is 5 for example index += 1 every 5 second/ the animation makes a loop every 5 second.


Solution

  • You can use setInterval() like this

    index = 0;
    function animate() {
        index++;
        console.log(index)
        //requestAnimationFrame(animate);
    }
    
    setInterval(function(){  
      animate();
    }, 5000);