Is There a Sleep Function in JavaScript

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));

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>);

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/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
...
window.setTimeout(partB,1000);
}

function partB() {
...
}

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Why doesn't Javascript have a sleep function?

It does. It's called setTimeout().

The common JavaScript environments (the browser and node.js) are single threaded and event driven. They need to keep servicing their main event loop. Just flat out stopping the thread will stop the background processes as well, since it depends on the event loop firing.

This is common in just about all user-facing environments; Windows, Mac OS, Java swing, Android etc. all require you to keep the main UI thread running; you can't just sleep() on it.

Why there is no sleep functionality in javascript when there is setTimeout and setInterval?

I think 'sleep'ing is something you do not want in your browser.

First of all it might be not clear what has to happen and how a browser should behave when you actually sleep.

  • Is the complete Script runtime sleeping? Normally it should because you only have one thread running your code. So what happens if other events oocur during sleep? they would block, and as soon execution continues all blocked events would fire. That will cause an odd behaviour as you might imagine (for instance mouse click events which are fired some time, maybe seconds, after the actual click). Or these events had to be ignored, which will lead to a loss of information.

  • What will happen to your browser? Shall it wait for sleep if the user clicks a (e.g. close window) button? I think not, but this might actually call javascript code again (unload) which will not be able to be called since program execution is sleeping.

On a second thought sleep is a sign of poor program design. Actually a program/function/you name it has a certain task, which shall be completed as soon as possible. Sometimes you have to wait for a result (for instance you wait for an XHR to complete) and you want to continue program execution meanwhile. In this case you can and should use asynchronous calls. This results in two advantages:

  • The speed of all scripts is enhanced (no blocking of other scripts due to sleep)
  • The code is executed exactly when it should and not before or after a certain event (which might lead to other problems like deadlocks if two functions check for the same condition ...)

... which leads to another problem: Imagine two or more pieces of code would call sleep. They would hinder themselves if they try to sleep at the same, maybe unnecessarily. This would cause a lot of trouble when you like to debug, maybe you even have difficulties in ensuring which function sleeps first, because you might control this behavior somehow.

Well I think that it is one of the good parts of Javascript, that sleep does not exist. However it might be interesting how multithreaded javascripts could perform in a browser ;)

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));

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>);

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));

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>);

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();

Add Timeout / Sleep function inside javascript loop

You can make use of ES6's async/await-feature!

To use await, it needs to be in a function/expression body declared async.

Basically, this will make your function be asynchronous, and make it wait for a Promise to be fulfilled. We make that Promise be fulfilled after a set delay using setTimeout().

Note that "after a set delay" does not mean "exactly after", it basically means "as early as possible after".

By doing this, the asynchronous function waits for the promise to be fulfilled, freeing up the callstack in the meantime so that other code can be executed.

The order of execution of this example is (simplified) as follows:

  1. sleepingFunc() is placed on callstack
    • In iteration: await for Promise to be fulfilled, suspending this call freeing up callstack
  2. Place new calls on callstack
  3. Eventually, Promise is fulfilled, ending await place suspended call back on callstack
  4. Repeat until sleepingFunc() finished

As you can see in step 3, if other calls take up more time than the delay, the suspended call will have to wait that extra time longer.

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

async function sleepingFunc() {
for (let i = 0; i < 5; ++i) {
console.log(i + " - from sleep");
await sleep(1000);
}
}

function synchronousFunc() {
for (let i = 0; i < 5; ++i) {
console.log(i + " - from sync");
}
}

sleepingFunc();
synchronousFunc();


Related Topics



Leave a reply



Submit