1const sleep = (milliseconds) => {
2 return new Promise(resolve => setTimeout(resolve, milliseconds))
3}
4
5/*Use like so*/
6
7async function timeSensativeAction(){ //must be async func
8 //do something here
9 await sleep(5000) //wait 5 seconds
10 //continue on...
11}
1function sleep(milliseconds) {
2 const date = Date.now();
3 let currentDate = null;
4 do {
5 currentDate = Date.now();
6 } while (currentDate - date < milliseconds);
7}
8
9console.log("Hello");
10sleep(2000);
11console.log("World!");
1function sleep(ms) {
2 return new Promise(resolve => setTimeout(resolve, ms));
3}
4
5async function demo() {
6 console.log('Taking a break...');
7 await sleep(2000);
8 console.log('Two seconds later, showing sleep in a loop...');
9
10 // Sleep in loop
11 for (let i = 0; i < 5; i++) {
12 if (i === 3)
13 await sleep(2000);
14 console.log(i);
15 }
16}
17
18demo();
1function sleepFor( sleepDuration ){
2 var now = new Date().getTime();
3 while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
4}
5
6// Use like so:
7
8sleepFor(1000)
9alert("hi")
1// Sync version
2function sleep(sleepDuration){
3 var now = new Date().getTime();
4 while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
5}