How to make browser console wait in javascript

I'm trying to make a script that clicks a page button, waits for X seconds (for the result to be done), and then continues.

How can i do this? (only part of the wait)

+3


source to share


2 answers


using setTimeout which is executed only once after the delay

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

      

using setInterval, which is re-executed after the delay



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

      

clearTimeout is used to clear them !!!

+6


source


You want to use setTimeout()

that executes a piece of code 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>
      

Run codeHide result




Or you can use setInterval()

that calls a function or executes a piece of code multiple times, with a fixed time delay between each call to the function:

function KeepSayingHello(){
  setInterval(function () {alert("Hello")}, 3000);
}
      

<button onclick="KeepSayingHello()">Click me to keep saying hello every 3 seconds</button>
      

Run codeHide result


+3


source







All Articles