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!");
1async function init() {
2 console.log(1);
3 await sleep(1000);
4 console.log(2);
5}
6
7function sleep(ms) {
8 return new Promise((resolve) => {
9 setTimeout(resolve, ms);
10 });
11}
12
13// one liner
14let sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
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();
1//Javascipt is asyncronous so you can't pause/block code execution
2//You can delay doing something with setTimeout
3setTimeout(function(){
4 alert("Sup!");
5}, 2000);//wait 2 seconds