Is there a way I can do a sleep in JavaScript before it carries out another action?
Example:
var a = 1+3;
// Sleep 3 seconds before the next action
The latest Safari, Firefox and Node.js are now also supporting async/await/promises.
(As of 1/2017, supported on Chrome, but not on Safari, Internet Explorer, Firefox, Node.js)
'use strict';
function sleep(ms) {
return new Promise(res => setTimeout(res, ms));
}
let myAsyncFunc = async function() {
console.log('Sleeping');
await sleep(3000);
console.log('Done');
}
myAsyncFunc();
JavaScript has evolved since this question was asked and now has generator functions, and the new async/await/Promise is being rolled out. Below there are two solutions, one with generator function that will work on all modern browsers, and another, using the new async/await that is not yet supported everywhere.
'use strict';
let myAsync = (g) => (...args) => {
let f, res = () => f.next(),
sleep = (ms) => setTimeout(res, ms);
f = g.apply({sleep}, args); f.next();
};
let myAsyncFunc = myAsync(function*() {
let {sleep} = this;
console.log("Sleeping");
yield sleep(3000);
console.log("Done");
});
myAsyncFunc();
Pay attention to the fact that both these solutions are asynchronous in nature. This means that the myAsyncFunc (in both cases) will return while sleeping.
It is important to note that this question is different than What is the JavaScript version of sleep()? where the requestor is asking for real sleep (no other code execution on the process) rather than a delay between actions.