Sleep Function In JavaScript | Async/Sync

Sleep Function In JavaScript | Async/Sync


0






Rahul Kumar (@rahul)

Dive straight into practical coding with our blog post on implementing a sleep function in JavaScript. No lengthy explanations, just pure code examples for both asynchronous and synchronous scenarios.

Asynchronous Sleep

Asynchronous Sleep

      /**
* Delay for a number of milliseconds
*/
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

console.log('Hello');
sleep(2000)
.then(() => { 
     console.log('World!'); 
});
    

Synchronous Sleep

A naive, CPU-intensive method to block execution for several milliseconds:

Synchronous Sleep

      /**
* Delay for a number of milliseconds
*/
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

console.log('Hello');
sleep(2000);
console.log('World');
    

Add a thoughtful comment...

✨ Explore more tech insights and coding wonders with @dsabyte! Your journey in innovation has just begun. Keep learning, keep sharing, and let's continue to code a brighter future together. Happy exploring! 🚀❤️

  • #nodejs
  • #javascript
  • #asynchronous
  • #synchronous
  • #hello

Subscribe to our newsletter.

Join the "News Later" community by entering your email. It's quick, it's easy, and it's your key to unlocking future tech revelations.

Weekly Updates

Every week, we curate and deliver a collection of articles, blogs and chapters directly to your inbox. Stay informed, stay inspired, and stay ahead in the fast-paced world of technology.

No spam

Rest assured, we won't clutter your inbox with unnecessary emails. No spam, only meaningful insights, and valuable content designed to elevate your tech experience.

© 2024 @dsabyte. All rights reserved