Hello Folks π
What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer.
Today, I am here again with an amazing topic that you'll love reading. So let's gets started π
π Introduction
By default, Javascript doesn't come with the sleep()
function. To implement sleep timers, setTimeout()
function is the closest equivalent to the sleep()
function. There, are other few less common ways to implement a sleep function to create a pause after some specified duration of the time.
setTimeout
setTimeout()
sets a timer for a function that executes the code once after the time expires. The only code that is inside the setTimeout()
function will execute after the given amount of time. Duration is always written in milliseconds(ms). Here's how you write the setTimeout()
function.
const printHelloWorld = () => {
console.log("Hello");
setTimeout(() => console.log("World"), 500);
};
printHelloWorld(); // "Hello", "World" ("World" logs after 500ms)
Synchronous method
Here, we can use a loop to stop the execution of the function
const sleep = (ms) => {
const stop = new Date().getTime() + ms;
while (new Date().getTime() < stop) {}
}
const printHelloWorld = () => {
console.log("Hello");
sleep(500)
console.log("World")
};
printHelloWorld(); // "Hello", "World" ("World" logs after 500ms)
Asynchronous method
A less interfering method to implement the sleep()
function using the async
and await
and a setTimeout()
and Promise
. Since we are dealing with the Promise
the executing function must be async
.
const sleep = (ms) =>
new Promise(resolve => setTimeout(resolve, ms));
const printHelloWorld = () => {
console.log("Hello");
sleep(500)
console.log("World")
};
printHelloWorld(); // "Hello", "World" ("World" logs after 500ms)
So, this was it for this article. I hope you learnt something new and enjoy reading. Stay tuned for the next article.
Let's connect on Twitter - @codewithsnowbit
Top comments (0)