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}
1How to get a JavaScript sleep function
2
3First, you must sacrifice JS to the gods of asynchronous programming.
4Then, go to grepper and ctrl c + v some code with no idea how to use it.
5Give up.
6Realise you didnt need it in the first place.
7Die inside a little.
8Realise you should have stayed with python.
9Learn Java out of frustration.
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();
1sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
2
3// V Must add this async keyword
4sayHi = async () => {
5 // V Must include await
6 await sleep(1000); // Sleep 1000 milliseconds (1 second)
7 console.log('Hi');
8 // Rest of code...
9}
1//Implement sleep function
2function sleep(milliseconds) {
3 return new Promise((resolve) => {
4 setTimeout(resolve, milliseconds);
5 });
6}
7
8//How to use sleep function
9async function delayedGreeting() {
10 console.log("Hello");
11
12 await sleep(2000); //2 Seconds
13
14 console.log("World!");
15}
16
17delayedGreeting();
18