2621. Leetcode - Sleep Solution
IntuitionThe problem requires us to create a sleep function that delays execution for a given number of milliseconds before resolving. Since JavaScript is async
# **Intuition**  

The problem requires us to create a **`sleep` function** that delays execution for a given number of milliseconds before resolving. Since JavaScript is **asynchronous and single-threaded**, we cannot use a traditional blocking sleep (like Python’s `time.sleep()`). Instead, we use **Promises and `setTimeout()`** to introduce a delay efficiently.  

---

# **Understanding `setTimeout()` in JavaScript**  

### 🔹 **What is `setTimeout()`?**  
`setTimeout()` is a **built-in JavaScript function** used to execute code **after a specified delay**. It does not pause execution but schedules a callback function to run later.  

### 🔹 **Syntax:**  
```js
setTimeout(callback, delay);
```
- `callback` – The function to execute after the delay.  
- `delay` – The time in milliseconds to wait before executing `callback`.  

### 🔹 **Example:**  
```js
console.log("Start");
setTimeout(() => console.log("Delayed execution"), 2000);
console.log("End");
```
📌 **Output:**  
```
Start  
End  
Delayed execution (after 2 sec)
```
**Why?**  
- JavaScript does **not** wait for `setTimeout()` to finish before moving to the next statement.  
- This is because JavaScript is **non-blocking and event-driven**.  

---

# **Approach**  

### 🔹 **Approach 1: Using `await` with `setTimeout()` (Alternative)**  

```js
async function sleep(millis) {
    await new Promise((resolve) => setTimeout(resolve, millis));
}
```
📌 **Explanation:**  
- Creates a **new Promise** that resolves after `millis` milliseconds.  
- Uses `setTimeout(resolve, millis)` to **schedule** the resolution.  
- The `await` ensures that execution **pauses** until the promise resolves.  
- **Simple and effective!** ✅  

---

### 🔹 **Approach 2: Using Explicit `reject` Parameter (Main Code) 🚀**  

```js
/**
 * @param {number} millis
 * @return {Promise}
 */
async function sleep(millis) {
    await new Promise((resolve, reject) => {
        setTimeout(resolve, millis);
    });
}

/** 
 * let t = Date.now()
 * sleep(100).then(() => console.log(Date.now() - t)) // ~100ms
 */
```
📌 **Why use `reject`?**  
- While not needed for this case, adding `reject` is a **best practice** in case we need error handling in the future.  
- This approach ensures better **scalability** if additional logic needs to be added inside `setTimeout()`.  

---

# **Complexity Analysis**  

- **Time Complexity:**  
  - ⏳ **O(1)** (The delay is constant, independent of input size).  
- **Space Complexity:**  
  - 🗂️ **O(1)** (No extra data structures used).  

---

# **Code Implementation**  

```js
/**
 * @param {number} millis
 * @return {Promise}
 */
async function sleep(millis) {
    await new Promise((resolve, reject) => {
        setTimeout(resolve, millis);
    });
}
```

---

# **Important Topics to Learn 📚**  

✅ **JavaScript Promises & Async/Await**  
✅ **Understanding `setTimeout()`**  
✅ **Handling Delays Without Blocking Execution**  
✅ **JavaScript Event Loop & Concurrency**  

---

# 🚀 **Support & Feedback**  

✅ If you found this helpful, **please upvote & comment** on my solution!  
💬 Let’s discuss alternative solutions & improvements! 🚀  
['JavaScript']