JavaScript has evolved significantly since the time this query was raised. 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();
Note that await can only be executed in functions prefixed with the async keyword, or at the top level of your script in an increasing number of environments. Additionally, wait only pauses the current async function. This means it does not block the execution of the rest of the script, which is what you want in the vast majority of the cases.