xxxxxxxxxx
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
/*Use like so*/
async function timeSensativeAction(){ //must be async func
//do something here
await sleep(5000) //wait 5 seconds
//continue on...
}
xxxxxxxxxx
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
console.log("Hello");
sleep(2000);
console.log("World!");
xxxxxxxxxx
console.log("Hello");
setTimeout(() => { console.log("World!"); }, 5000);
console.log("Goodbye!");
xxxxxxxxxx
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function delayedGreeting() {
console.log("Hello");
await sleep(2000);
console.log("World!");
await sleep(2000);
console.log("Goodbye!");
}
delayedGreeting();
xxxxxxxxxx
//Javascipt is asyncronous so you can't pause/block code execution
//You can delay doing something with setTimeout
setTimeout(function(){
alert("Sup!");
}, 2000);//wait 2 seconds
xxxxxxxxxx
sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
// V Must add this async keyword
sayHi = async () => {
// V Must include await
await sleep(1000); // Sleep 1000 milliseconds (1 second)
console.log('Hi');
// Rest of code...
}
xxxxxxxxxx
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
console.log('First');
sleep(1000);
console.log('Second');
xxxxxxxxxx
// sleep time expects milliseconds
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
// Usage!
sleep(500).then(() => {
// Do something after the sleep!
});
xxxxxxxxxx
How to get a JavaScript sleep function
First, you must sacrifice JS to the gods of asynchronous programming.
Then, go to grepper and ctrl c + v some code with no idea how to use it.
Give up.
Realise you didnt need it in the first place.
Die inside a little.
Realise you should have stayed with python.
Learn Java out of frustration.