Home > Mobile >  JavaScript: Repeated EventListener when created in a for loop
JavaScript: Repeated EventListener when created in a for loop

Time:01-27

my code depends on creating an EventListener inside a loop then removing it after the function is done, yet somehow on the Eventlitesning is repeated after each loop execution, my code looks something like:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- <link href="css/style.css" rel="stylesheet"> -->
    </head>
    <body>
        <button id="btn" onclick="fun()">button</button>
    </body>
    <script>
        const btn=document.getElementById("btn");
        console.log(btn);
        function fun(){
            for (let i = 0; i < 5; i  ) {
                btn.addEventListener("click", ()=>{alert(`warning NO.${i}`)});
                
                //code to be executed
                
                btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
            }
        }
    </script>
</html>

the first time I press the button the 5 warning messages appear and the second time I press the button the 5 warnings messages appear twice, an dun the third time it appears 3 times, and so on.

I'd be very grateful if anyone could support me in this issue.

I tried to do the following but it didn't work either:

        const btn=document.getElementById("btn");
       
        function fun(){
            for (let i = 0; i < 5; i  ) {
                btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});

                btn.addEventListener("click", ()=>{alert(`warning NO.${i}`)});
                
                //code to be executed
                
                btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
            }
        }

CodePudding user response:

Does this code satisfy your requirement?
Note: onclick() itself is an event listener.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- <link href="css/style.css" rel="stylesheet"> -->
    </head>
    <body>
        <button id="btn" onclick="fun()">button</button>
    </body>
    <script>
        function fun(){
            for (let i = 0; i < 5; i  ) {
                alert(`warning NO.${i}`);
            }
        }
    </script>
</html>

  • Related