What Is the JavaScript Version of Sleep()

What is the JavaScript version of sleep()?

2017 — 2021 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Or as a one-liner:

await new Promise(r => setTimeout(r, 2000));

Or

const sleep = ms => new Promise(r => setTimeout(r, ms));

Use it as:

await sleep(<duration>);

Demo:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}

demo();

What is the JavaScript version of sleep()?

2017 — 2021 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Or as a one-liner:

await new Promise(r => setTimeout(r, 2000));

Or

const sleep = ms => new Promise(r => setTimeout(r, ms));

Use it as:

await sleep(<duration>);

Demo:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}

demo();

What is the JavaScript version of sleep()?

2017 — 2021 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Or as a one-liner:

await new Promise(r => setTimeout(r, 2000));

Or

const sleep = ms => new Promise(r => setTimeout(r, ms));

Use it as:

await sleep(<duration>);

Demo:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}

demo();

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

What is the JavaScript version of sleep()?

2017 — 2021 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Or as a one-liner:

await new Promise(r => setTimeout(r, 2000));

Or

const sleep = ms => new Promise(r => setTimeout(r, ms));

Use it as:

await sleep(<duration>);

Demo:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}

demo();

Javascript Delay/Sleep function

Just add the event listener, remove it after it's called, then set a timeout to add it again.

function scrollHandler() {
window.removeEventListener('scroll', scrollHandler);

// Detects new state and compares it with the old one
if ((document.body.getBoundingClientRect()).top > iniState)
console.log('up');
else
console.log('down');

// Saves the new position for iteration.
iniState = (document.body.getBoundingClientRect()).top;

setTimeout(() => window.addEventListener('scroll', scrollHandler), 2000);
}

window.addEventListener('scroll', scrollHandler);

How to skip/ clear this sleep() function?

In this case you don't need to cancel the timeout, just ignore it when it fires

Have global (can be namespace'd of course) variable that you set to true/false when you start and false/true when you want to stop.

Updated snippet using true(active) / false(stopped).

You could also use the opposite var cancelled = false; then set it to true when you click and check for false.

var active;

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

$('#target').click(function(e) {
e.preventDefault();
// try to stop the countdown
active = false;
});

async function start() {
active = true;
for (index = 0; index < 5; index++) {
await sleep(1000);
if (!active)
break;
$('#timer').text(index);
}
}

start();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 100px; height:100px; background-color: red" id="target"></div>
<div id="timer"></div>

How to make a precise sleep function in Javascript, possibly using promises?

Even if setTimeout did work on such extremely small time frames this would probably not have worked out. When you use callbacks and/or promises you rely of JS runtime's event loop. This event loop only executes your callback as fast as it can. The architecture is going to impose lags that will become visible when you go below 1ms. The callback in setTimeout is not exactly executed after N ms passes. After N ms passes it only becomes eligible to be executed. And it gets invoked finally only when its turn comes on another event loop tick.

As for your second approach it does not exactly "use up resources". The thing is you no longer use event loop. But you must remember that JS is single-threaded. And because of it when JS-code executes non-stop it will not let user interact with UI at all. User can do something only between event callback executions. So don't ever use long running whiles in JS in browser unless you want to ruin user experience. Maybe unless you use Web workers because they will let you create new threads, but then you wouldn't be able to draw anything from there.

In general your approach to animation as "drawing something and then sleeping" is rather naive. Performant and smooth animations are what the video cards are made for although writing it in browser to efficiently utilize video card may be tricky. If you want to make animation in browser then you have to find specific browser function calls made specifically for animation on a Canvas or WebGL.
Maybe start here:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations

Also think about if you actually need so may frames per second. Over 1000fps? Can the monitor make it? What about performance impact?

Javascript sleep/delay/wait function

You cannot just put in a function to pause Javascript unfortunately.

You have to use setTimeout()

Example:

function startTimer () {
timer.start();
setTimeout(stopTimer,5000);
}

function stopTimer () {
timer.stop();
}

EDIT:

For your user generated countdown, it is just as simple.

HTML:

<input type="number" id="delay" min="1" max="5">

JS:

var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;

function startTimer () {
timer.start();
setTimeout(stopTimer,delayInMilliseconds);
}

function stopTimer () {
timer.stop;
}

Now you simply need to add a trigger for startTimer(), such as onchange.



Related Topics



Leave a reply



Submit