Sleep in JavaScript - delay between actions
You can use setTimeout
to achieve a similar effect:
var a = 1 + 3;
var b;
setTimeout(function() {
b = a + 4;
}, (3 * 1000));
This doesn't really 'sleep' JavaScript—it just executes the function passed to setTimeout
after a certain duration (specified in milliseconds). Although it is possible to write a sleep function for JavaScript, it's best to use setTimeout
if possible as it doesn't freeze everything during the sleep period.
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();
How do I add a delay in a JavaScript loop?
The setTimeout()
function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.
You may want to use something like this instead:
var i = 1; // set your counter to 1
function myLoop() { // create a loop function
setTimeout(function() { // call a 3s setTimeout when the loop is called
console.log('hello'); // your code here
i++; // increment the counter
if (i < 10) { // if the counter < 10, call the loop function
myLoop(); // .. again which will trigger another
} // .. setTimeout()
}, 3000)
}
myLoop(); // start the loop
Delay Action in Javascript without stopping the rest of the code
You cannot do what you want the way you want it. JavaScript is designed not to have "a sleep function".
From what you said it seems you have a check inside an animation frame handler that tests whether a button is pressed, and to trigger an action if it is. In order to prevent this action from triggering for the next three seconds, simply check if it has been three seconds since the action last triggered:
let lastAttack = null;
// ...
if (self.pressingAttack) {
let now = new Date();
if (!lastAttack || now - lastAttack > 3000) {
self.shootBullet(self.mouseAngle);
lastAttack = now;
}
}
How can I wait In Node.js (JavaScript)? l need to pause for a period of time
Update Jan 2021: You can even do it in the Node REPL interactive using --experimental-repl-await
flag
$ node --experimental-repl-await
> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
> await delay(1000) /// waiting 1 second.
A new answer to an old question. Today ( Jan 2017 June 2019) it is much easier. You can use the new async/await
syntax.
For example:
async function init() {
console.log(1);
await sleep(1000);
console.log(2);
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
For using async/await
out of the box without installing and plugins, you have to use node-v7 or node-v8, using the --harmony
flag.
Update June 2019: By using the latest versions of NodeJS you can use it out of the box. No need to provide command line arguments. Even Google Chrome support it today.
Update May 2020:
Soon you will be able to use the await
syntax outside of an async function. In the top level like in this example
await sleep(1000)
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
The proposal is in stage 3.
You can use it today by using webpack 5 (alpha),
More info:
- Harmony Flag in Nodejs: https://nodejs.org/en/docs/es6/
- All NodeJS Version for download: https://nodejs.org/en/download/releases/
Is there a sleep function in JavaScript?
You can use the setTimeout
or setInterval
functions.
Add a time delay between to actions of the same function?
Use setTimeout
for providing delay
function myFunction() {
document.getElementById('box1').style.display = "block";
setTimeout(function() {
// code to execute after delay
$("#box2").data("mmenu").close();
}, 2000);
// -^- delay in milliseconds
};
How to set time delay in javascript
Use setTimeout()
:
var delayInMilliseconds = 1000; //1 second
setTimeout(function() {
//your code to be executed after 1 second
}, delayInMilliseconds);
If you want to do it without setTimeout
: Refer to this question.
Related Topics
Chained Promises Not Passing on Rejection
Correct Try...Catch Syntax Using Async/Await
Evaluating a String as a Mathematical Expression in JavaScript
How to Chain and Share Prior Results With Promises
Get Computed Font-Family in JavaScript
How to Check If an External (Cross-Domain) CSS File Is Loaded Using JavaScript
Combination of Animation and Transition Not Working Properly
Phonegap - Save Image from Url into Device Photo Gallery
Is There a JavaScript Function That Can Pad a String to Get to a Determined Length
How to Define Global Variables in Coffeescript
What Is This JavaScript "Require"
How to Match a Whole Word in JavaScript
How to Determine If a Variable Is 'Undefined' or 'Null'
Is There a Case Insensitive Jquery :Contains Selector
Read CSS Property of an Element Using JavaScript
How to Detect CSS3 Resize Events