Search code examples
javascriptperformancelag

Why does my Javascript Canvas Point & Click game get slower after a few minutes?


I tried disabling some features including all audio effects and background music elements but it still gets slower. Am I not resetting Timeouts and Intervals properly? Hmm... the only place where addEventListener is called in update is

This code is called inside an animation update loop:

bgm8.addEventListener('ended', function () {
            this.currentTime = 0;
            this.play();
        }, false);

Hmm... I have a very heavy emphasis on DOM usage. Nearly half of every page is covered in document.getElementById. Would this slow the game down more and more after a few minutes though? Maybe it really is setTimeouts and setIntervals that is the problem? Here is one example of code I use for a setTimeout:

setTimeout(() => {
                        document.getElementById("showerDoor1").play();
                        setTimeout(() => {
                            document.getElementById("erlik1").play();
                        }, 1000);
                    }, 1000);

Could it be placing import statements at the top of relative script files? This import code is from room104_init.js:

import { Background } from './background.js';
import { EventZones } from './eventZones.js';
import { ClickEvents } from './clickEvents.js';
import { WaterDrop, Tile } from '../common/roomObjects.js';

I tried disabling most of the features and the game still lags after a few minutes. I just don't get it.


Solution

  • "This code is called inside an animation update loop:" looks like the problem. Don't add event listeners for the same event in a loop without removing the previous event listener (which will need a reference to the listener function to remove it). Otherwise, as even more and more event listeners are added for the same event, processing slows down or stops.

    The solution is to add event listeners outside of any loop or, as commented, supply a {once: true} options object when adding the event listener.