How to make browser console wait in javascript
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 to share
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>
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>
+3
source to share