DEV Community

Cover image for Javascript Implement a synchronous sleep #8
chandra penugonda
chandra penugonda

Posted on

Javascript Implement a synchronous sleep #8

This problem was asked by Amazon.

Please Implement a synchronous sleep() ?

*Example
*

sleep(3000);
console.log('>>> hi');

// output
>>> sleep start
// 3s later
>>> sleep finish
>>> hi
Enter fullscreen mode Exit fullscreen mode

Solution

function sleep(ms){
  console.log(">>> sleep start")
  let start = Date.now()
  while(start+ms > Date.now()){
    // so something
  }
  console.log('>>> sleep finish');
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Use Date.now() to get the start time before the sleep.
  • Loop while checking Date.now() - start to see if ms time has elapsed.
  • The loop essentially pauses execution for the given ms by doing nothing.
  • After the loop finishes, execution resumes normally.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay