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

22.9k views Asked by At

I’m trying to make a script that clicks on a page button, waits X seconds (for the result of the click to take place), and then continues.

How can I implement the waiting part?

3

There are 3 answers

2
Shushanth Pallegar On BEST ANSWER

using setTimeout, which executes only once after the delay provided

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

using setInterval , which executes repeatedly after the delay provided

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

clearTimeout and clearInterval is used to clear them up !!!

2
programking On

You want to use setTimeout() which executes a code snippet after a specified delay.:

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>

Or you can use setInterval() which calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function:

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

0
bob chen On

Somehow setTimeout doesn't do anything for me. But window.setTimeout does.

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