Search code examples
javascriptjquerytampermonkey

Function running twice using setdelay


My function is running twice , I tried using boolean value to stop it but it doesn't work, here is my code :

     window.onload = function(){
   setTimeout(addbutton, 2940) // Please increase it if it doesn't work, it doesn't work well if your connection is too long
};
function addbutton(){
var hreflink = "/admin/users/delete/"+id;
var Reportuser = document.getElementsByClassName("sg-button sg-button--solid-light sg-button--full-width");
var x = Reportuser.length-1
Reportuser[x].insertAdjacentHTML('beforebegin', '<button id=button class="sg-button sg-button--solid-mint sg-button--small sg-button"><span class="sg-button__text">Delete</span></button>');
console.log("%cButton added","color: blue; font-size: 20px");

function myFunction() {
window.location.href = hreflink;
}
document.getElementById("button").addEventListener("click", myFunction);

}

Solution

  • Refactored and converted your code to a minimal reproducable example using event delegation. The timeout works, once. If you are experiencing problems with connection times, maybe you should check async functions

    setTimeout(addbutton, 500);
    
    document.addEventListener("click", handle); 
    
    function handle(evt) {
      if (evt.target.dataset.clickable) {
        console.clear();
        return console.log("Yes! It's clicked!");
      }
      return true;
    }
    
    function addbutton() {
      [...document.querySelectorAll(".sg-button")].pop()
        .insertAdjacentHTML("beforeend", `<button data-clickable="1">Delete</button>`);
      console.log("button added to last div.sg-button ...");
    }
    .sg-button {
      margin-bottom: 1.5rem;
      border: 1px solid #999;
      padding: 0.2rem;
      width: 5rem;
      text-align: center;
    }
    
    .sg-button button {
      display: block;
      margin: 0 auto;
    }
    <div class="sg-button sg-button--solid-light sg-button--full-width">1</div>
    <div class="sg-button sg-button--solid-light sg-button--full-width">2</div>