IsharM
IsharM

Reputation: 153

Cancel the requestAnimationFrame loop after some time

I want to cancel an animation after a timeout. Here's my code

function animate(){
        id = requestAnimationFrame(animate);
        console.log(id);
        c.clearRect(0,0, window.innerWidth, window.innerHeight);
        for(let i = 0; i < circleArray.length; i++){
            circleArray[i].scatter();
        }
        setTimeout(function(){
            id = requestAnimationFrame(animate);
            cancelAnimationFrame(id);
            update();
        },5000)
    }
    
    function update(){
        requestAnimationFrame(update);
        c.clearRect(0,0, window.innerWidth, window.innerHeight);
        for(let i = 0; i < circleArray.length; i++){
            circleArray[i].update();
        }
    }

Here, I want to stop the recursion of the animate function and start the update function. But the animate doesnt stop and update function runs concurrently after the given time.

Upvotes: 1

Views: 673

Answers (1)

Blindman67
Blindman67

Reputation: 54026

Just use a variable to reference the current render function and change that variable on the timer event.

Example

var currentFrameRender = animate;  // set current render
requestAnimationFrame(currentFrameRender); // request first frame
setTimeout(() => currentFrameRender = update ,5000); // switch render in 5s
setTimeout(() => currentFrameRender = undefined ,10000); // stop animation in 10s

function animate(){
    c.clearRect(0, 0, c.canvas.width, c.canvas.height);
    for(let i = 0; i < circles.length; i++){
        circleArray[i].scatter();
    }

    // request frame only if currentFrameRender is defined
    currentFrameRender && requestAnimationFrame(currentFrameRender);
}

function update(){
    c.clearRect(0, 0, c.canvas.width, c.canvas.height);
    for(let i = 0; i < circles.length; i++){
        circleArray[i].update();
    }

    // request frame only if currentFrameRender is defined
    currentFrameRender && requestAnimationFrame(currentFrameRender);
}

Upvotes: 1

Related Questions