How to make a browser console wait in a javascript
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>