
Sponsored
Sponsored
This approach utilizes JavaScript's Promise and setTimeout to create an asynchronous sleep function. The setTimeout function is used to delay the promise resolution by the specified number of milliseconds.
Time Complexity: O(1) because the delay is constant independent of any input size.
Space Complexity: O(1) as we're only storing the promise which requires constant space.
1function sleep(millis) {
2 return new Promise(resolve The sleep function creates a new Promise. Inside the promise, setTimeout is used to delay the invocation of the resolve function by millis milliseconds. This means the promise will be resolved after the specified delay, implementing a "sleep" behavior.
This approach uses C#'s Task.Delay method to implement the asynchronous sleep function. Task.Delay returns a task that completes after the specified delay.
Time Complexity: O(1). The execution time is constant due to the non-blocking nature of tasks.
Space Complexity: O(1) as we're dealing with a single task object.
1using System.Threading.Tasks;
2
3public class Solution {
4 public async Task Sleep(int millis) {
5 await Task.Delay(millis);
6 }
7}In C#, the Sleep method is marked async to indicate it can execute asynchronously. We use Task.Delay, which returns a Task that completes after a delay specified by millis. The await keyword is used to asynchronously wait for the task's completion.
This method involves Java's CompletableFuture class which allows for asynchronous programming. We can use this to simulate a sleep by combining it with Thread.sleep.
Time Complexity: O(1). The delay action is constant time as it directly calls Thread.sleep.
Space Complexity: O(1) since the CompletableFuture only maintains a completion stage.
1import java.util.concurrent.CompletableFuture;
2import java.util.concurrent.TimeUnit;
3
4public class Solution {
5 public static CompletableFuture<Void> sleep(int millis) {
6 return CompletableFuture.runAsync(() -> {
7 try {
8 Thread.sleep(millis);
9 } catch (InterruptedException e) {
10 Thread.currentThread().interrupt();
11 }
12 });
13 }
14}The sleep function uses CompletableFuture.runAsync to execute a task asynchronously that sleeps for the given milliseconds using Thread.sleep. CompletableFuture handles asynchronous computations and allows us to define a function to be run asynchronously.
In Python, the asyncio library provides an asynchronous infrastructure, with asyncio.sleep providing sleep functionality without blocking.
Time Complexity: O(1). The delay is managed internally by the event loop, thus constant.
Space Complexity: O(1) as only the coroutine object is being utilized.
1import asyncio
2
3async def sleep(millis):
4 await asyncio.sleep(millis / 1000)The sleep function is asynchronous, using asyncio.sleep to suspend the coroutine for the specified duration. The function converts milliseconds to seconds (since asyncio.sleep accepts seconds) and then awaits the sleep.