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)