How to Wait 1 Second in Javascript

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'));
Code language: JavaScript (javascript)

Option 2 – Using setTimeout

setTimeout(function(){ console.log("Ready") }, 1000);
Code language: JavaScript (javascript)

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();
Code language: JavaScript (javascript)

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');
Code language: JavaScript (javascript)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments