试图获得一个按钮来使用函数执行 setTimeout

Trying to get a button to do setTimeout with a function

这是我第一次尝试使用 setTimeout,我使用 W3schools 作为指导,但我一定是在 onclick 行的某处出错了,我想做的是将此功能延迟 5 秒。这是我的代码。任何帮助深表感谢。如果它有助于功能在没有 setTimeout

的情况下按预期工作

function scanalertfunction(id) {
  var divelement1 = document.getElementById(id)

  document.getElementById("scanalertmsg").innerHTML = "Scan Failed! Please try again";
  divelement1.style.display == 'none'
  divelement1.style.display = 'block';
}
<div id="scanalert" style="display:none;">
  <span class="scanclosebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  <p id="scanalertmsg"> </p>
</div>
<button onclick="setTimeout(scanalertfunction('scanalert'); 5000);">Ready</button>

几乎没有语法错误

检查这个片段

function scanalertfunction(id) {
  var divelement1 = document.getElementById(id)

  document.getElementById("scanalertmsg").innerHTML = "Scan Failed! Please try again";
  divelement1.style.display == 'none'
  divelement1.style.display = 'block';
}
<div id="scanalert" style="display:none;">
  <span class="scanclosebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  <p id="scanalertmsg"> </p>
</div>
<button onclick="setTimeout(scanalertfunction('scanalert') ,5000);">Ready</button>

如 cyrix 所述,setTimeout 需要一个函数作为其参数。请参阅下面的工作解决方案。

function scanalertfunction(id) {
  var divelement1 = document.getElementById(id)

  document.getElementById("scanalertmsg").innerHTML = "Scan Failed! Please try again";
  divelement1.style.display == 'none'
  divelement1.style.display = 'block';
}
<div id="scanalert" style="display:none;">
  <span class="scanclosebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  <p id="scanalertmsg"> </p>
</div>
<button onclick="setTimeout(function() {scanalertfunction('scanalert'); },5000);">Ready</button>