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 do that? (only the wait part)
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
If you are looking to block the execution of code with call to sleep , then no, there is no method for that in JavaScript . JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.
Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.
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 !!!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With