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
Try this function:
const delay = (ms, cb) => setTimeout(cb, ms)
Here is how you use it:
console.log("Waiting for 5 seconds.")
delay(5000, function() {
console.log("Finished waiting for 5 seconds.")
})
Or go promise style:
const delay = ms => new Promise(resolve => {
setTimeout(resolve, ms)
})
Here's a demo.