是否有一个Javascript函数可以使代码在运行时延迟

Is there a Javascript function to make the code delay at the point that code run?

本文关键字:运行时 延迟 代码 可以使 有一个 Javascript 函数 是否      更新时间:2023-09-26

好的,我得到了这个<button onclick="alert('1');setInterval(function(){},57000);alert('2');"> Show </button>

拖延没有起作用。

setTimeout也不起作用。

如何修复

将警报放入setInterval回调:

<button onclick="alert('1');setInterval(function(){alert('2');},57000);"> Show </button>

代码的简单扩展版本:

var div = document.querySelector('div');
function myFunction(){
  div.textContent += '-'; 
  // beware, this code might crash your browser if left running
  // for a few (thousand) years!!!
}
<button onclick="setInterval(myFunction, 1000);"> Start Interval </button>
<div></div>


上面代码的正确样式版本:

var div = document.getElementById('d');
var button = document.getElementById('b');
button.addEventListener('click', clickHandler);
function myFunction(){
  div.textContent += '-'; 
  // beware, this code might crash your browser if left running
  // for a few (thousand) years!!!
}
function clickHandler(){
  setInterval(myFunction, 1000);
}
<button id="b"> Start Interval </button>
<div id="d"></div>

  • 工作小提琴

JavaScript代码同步运行,这意味着每条指令都是一条接一条地执行的。让我们看看你的代码:

alert('1');
setInterval(function(){
    //does nothing
}, 57000);
alert('2');

现在,每一行都将一个接一个地执行,这意味着alert(1)将执行,然后是setInterval(...),再是alert(2)。您的setInterval不会停止其他行的执行。

如果您想延迟代码执行,则必须考虑在setInterval(我假设您想在此处使用setTimeout)完成后执行

此外,作为一名专业人员,您应该将JavaScript代码与HTML分离。让我们考虑以下内容:

<button id="myButton">Show</button>
...
<script>
// Get a reference to your button
var myButton = document.querySelector('#myButton');
// The code you want to execute after the given time
function executeLater(){
    alert(2);
}
// We attach an event listener to your button
myButton.addEventListener('click', function(){
    alert('1');
    setTimeout(executeLater, 2000);
});
</script>