12

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Daniel Möller
  • 84,878
  • 18
  • 192
  • 214

3 Answers3

15

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 !!!

Shushanth Pallegar
  • 2,832
  • 1
  • 14
  • 16
  • This worked very well! I would suggest inserting "//logic" after console.log on your second example for clarity. Also, would help to show an example with the syntax for using "clearTimeout." Thanks for the great answer. – Jvieitez Oct 15 '17 at 08:04
  • It is working in console fine but I want to use it with a script for chrome extension, it doesn't work through extension script. – A.Aleem11 Oct 16 '19 at 21:57
3

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>
programking
  • 1,376
  • 1
  • 17
  • 32
-1

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

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