Synchronous delay in code execution
Variation on the accepted answer which is just as good as this one.
Also, I agree with the caveats of preferring setTimeout
and asynchronous function calling but sometimes e.g., when building tests, you just need a synchronous wait command...
function wait(ms) { var start = Date.now(), now = start; while (now - start < ms) { now = Date.now(); }}
if you want it in seconds, divide start ms by 1000 on the while check...
If you'd like to take advantage of the new async/await syntax, You can convert set timeout to a promise and then await it.
function wait(ms) { return new Promise((resolve, reject) => { setTimeout(() => { console.log("Done waiting"); resolve(ms) }, ms ) })} (async function Main() { console.log("Starting...") await wait(5000); console.log("Ended!")})();
Synchronous wait (only for testing!):
const syncWait = ms => { const end = Date.now() + ms while (Date.now() < end) continue}
Usage:
console.log('one')syncWait(5000)console.log('two')
Asynchronous wait:
const asyncWait = ms => new Promise(resolve => setTimeout(resolve, ms))
Usage:
(async () => { console.log('one') await asyncWait(5000) console.log('two')})()
Alternative (asynchronous):
const delayedCall = (array, ms) => array.forEach((func, index) => setTimeout(func, index * ms))
Usage:
delayedCall([ () => console.log('one'), () => console.log('two'), () => console.log('three'),], 5000)