java script sleep code example
Example 1: javascript sleep
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
async function timeSensativeAction(){
await sleep(5000)
}
Example 2: sleep js
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...');
for (let i = 0; i < 5; i++) {
if (i === 3)
await sleep(2000);
console.log(i);
}
}
demo();
Example 3: javascript sleep function
sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
sayHi = async () => {
await sleep(1000);
console.log('Hi');
}
Example 4: sleeping in js
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
sleep(2000);