What is javascript version of sleep()?

JavascriptObject Oriented ProgrammingFront End Technology

JavaScript does not have a native sleep function. There are however some workarounds you can use to get around this limitation. One of the easiest way to achieve sleep's functionality is to create your own sleep function using setTimeout and async/await.

Example

const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))
// Using callbacks
sleep(1000).then(() => console.log("waited 1 second!"))
// Using async await
const waitASec = async () => {
   await sleep(1000)
   console.log("waited 1 second!")
}
waitASec()

Output

waited 1 second!
waited 1 second!
raja
Published on 18-Sep-2019 13:51:01
Advertisements