requestAnimationFrame keeps running while its not called

Viewed 25

I am developing a js game and for the update() and draw() method I use requestAnimationFrame. ( I know i should use setInterval for the update). I have a time variable that uses the deltaTime and like that i update the game. When i stop the requsetanimationframe it keeps count again from the stop time. I used the cancelAnimationFrame but it doesnt work. Can someone help me fix the time issue.

let lastTime = 0, reqFrames = 0;

    window.restartGame = () => {
        window.game.resetAll();
        lastTime = 0;
        animate(0);
    }

    function animate(timeStamp){
        const deltaTime = timeStamp - lastTime;
        lastTime = timeStamp;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        window.game.update(deltaTime); // Here is where i update the game.time
        window.game.draw(ctx);
        if (!game.gameOver) {
            window.game.reqFrames = requestAnimationFrame(animate);
        }else{
            
        }
    }
    animate(0);
0 Answers
Related