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!");
//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
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');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two seconds later, showing sleep in a loop...');
// Sleep in loop
for (let i = 0; i < 5; i++) {
if (i === 3)
await sleep(2000);
console.log(i);
}
}
demo();
// sleep time expects milliseconds
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
// Usage!
sleep(500).then(() => {
// Do something after the sleep!
});
function sleepFor( sleepDuration ){
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
// Use like so:
sleepFor(1000)
alert("hi")
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two seconds later, showing sleep in a loop...');
// Sleep in loop
for (let i = 0; i < 5; i++) {
if (i === 3)
await sleep(2000);
console.log(i);
}
}
demo();
Run code snippetHide results
//Sleep funktion
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
//Or as a one-liner:
await new Promise(r => setTimeout(r, 2000));
//As a function:
const sleep = ms => new Promise(r => setTimeout(r, ms));
//or in Typescript:
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
//use it as:
await sleep(<duration>);