如何使代码在单击按钮后等待 X 秒,然后再继续

How to make code wait X seconds after clicking a button before continuing?

本文关键字:然后 再继续 等待 代码 何使 单击 按钮      更新时间:2023-09-26

我正在尝试制作一个脚本,单击页面按钮,等待 X 秒(单击结果发生),然后继续。

如何实现等待部分?

使用 setTimeout,在提供的延迟后仅执行一次

setTimeout(function(){
  console.log('gets printed only once after 3 seconds')
  //logic
},3000);

使用 setInterval ,它在提供的延迟后重复执行

setInterval(function(){
  console.log('get printed on every 3 second ')
},3000);

clearTimeoutclearInterval用于清除它们!!

你想使用setTimeout()在指定的延迟后执行代码片段。

var timeoutID;
function delayedAlert() {
  timeoutID = setTimeout(slowAlert, 2000);
}
function slowAlert() {
  alert("That was really slow!");
}
function clearAlert() {
  clearTimeout(timeoutID);
}
<p>Live Example</p>
<button onclick="delayedAlert();">Show an alert box after two seconds</button>
<p></p>
<button onclick="clearAlert();">Cancel alert before it happens</button>

或者,您可以使用setInterval()来调用函数或重复执行代码片段,每次调用该函数之间具有固定的时间延迟:

function KeepSayingHello(){
  setInterval(function () {alert("Hello")}, 3000);
}
<button onclick="KeepSayingHello()">Click me to keep saying hello every 3 seconds</button>

不知何故,setTimeout 对我没有任何作用。但是window.setTimeout确实如此。

window.setTimeout(function() {
  alert("Hello! This runs after 5 seconds delay!");
}, 5000);