yogas
yogas

Reputation: 209

javascript addEventListener for click event calls the functions multiple times

I have added an event Listener on click event for Html canvas element. The function statements gets executed multiple time. first time the statements execute once, when i call the main fnction again, the click causes same function to execute twice and then thrice and so on

Here is the listener

 function initializeNewGame() {

        // Set block 
        cur = new Date();
        countDownDate = new Date(cur.getTime() + 5*60010).getTime();
        moves = 0;
        BLOCK_WIDTH = Math.round(BLOCK_IMG_WIDTH / TOTAL_COLUMNS);
        BLOCK_HEIGHT = Math.round(BLOCK_IMG_HEIGHT / TOTAL_ROWS);

        document.getElementById("canJigsaw").addEventListener("click", myFunction);

        function myFunction() {
            moves = moves + 1;  

            } 

        SetImageBlock();

        DrawGame();
    }

Upvotes: 0

Views: 964

Answers (1)

Paul McBride
Paul McBride

Reputation: 318

Make sure that initializeNewGame is only called once. Each time it is called, it will add another click handler. This means that myFunction could be called multiple times for each click.\

Try adding a console log in the initializeNewGame to help detect if its called more than once.

Upvotes: 1

Related Questions