函数 运行 两次使用 setdelay

Function running twice using setdelay

我的函数是 运行 两次,我尝试使用布尔值来停止它但它不起作用,这是我的代码:

     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);

}

重构您的代码并将其转换为 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>