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
Solution
function sleep(ms){
console.log(">>> sleep start")
let start = Date.now()
while(start+ms > Date.now()){
// so something
}
console.log('>>> sleep finish');
}
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)