If you need your Javascript code to wait one (1) second (or more) while executing, then there are a couple of ways to achieve this.
Option 1 – Creating a delay
Promise
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
delay(1000).then(() => console.log('ran after 1 second elapsed'));
Option 2 – Using setTimeout
setTimeout(function(){
console.log("Ready")
}, 1000);
Option 3 – Using an async
Promise
async function test() {
console.log('start timer');
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('after 1 second');
}
test();
Option 4 – Creating a custom sleep
function
function sleep(num) {
let now = new Date();
const stop = now.getTime() + num;
while(true) {
now = new Date();
if(now.getTime() > stop) return;
}
}
sleep(1000)
console.log('delay 1 second');