Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a browser console wait in a javascript

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)

like image 809
Daniel Möller Avatar asked Jun 11 '15 18:06

Daniel Möller


People also ask

How do you wait 1 second in JavaScript?

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.

Is there a wait function in JavaScript?

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.

How do you wait for setTimeout?

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.


2 Answers

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

like image 180
Shushanth Pallegar Avatar answered Oct 10 '22 07:10

Shushanth Pallegar


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>
like image 28
programking Avatar answered Oct 10 '22 05:10

programking