JavaScript không có sleep() blocking như Python/Java. Phiên bản tương đương: await với Promise + setTimeout. await tạm dừng async function hiện tại (không block main thread).
Ví dụ: Sleep 5 giây
<!DOCTYPE html>
<html>
<body>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
document.write('Wait for 5 seconds!');
await sleep(5000); // Tạm dừng function này 5s
document.write('After 5 seconds!');
}
demo();
</script>
</body>
</html>
Cách dùng thực tế
// 1. Delay trong async function
async function fetchWithRetry(url, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await fetch(url);
} catch (e) {
if (i === retries - 1) throw e;
await sleep(1000 * Math.pow(2, i)); // Exponential backoff
}
}
}
// 2. Sequential vs Parallel
async function sequential() {
await sleep(1000);
await sleep(1000); // Tổng 2s
}
async function parallel() {
await Promise.all([sleep(1000), sleep(1000)]); // Tổng 1s
}
// 3. Throttle/Debounce helper
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Lưu ý quan trọng
awaitchỉ dùng trongasync function (hoặc top-level module).- Không block main thread - event loop vẫn xử lý event khác (UI responsive).
- Không dùng
while(Date.now() < target)busy-wait - freeze browser! - Top-level await:
<script type="module"> await sleep(1000); </script>(ES2022).
So sánh
| Language | Sleep | Behavior |
|---|---|---|
| Python | time.sleep(5) | Block thread 5s |
| Java | Thread.sleep(5000) | Block thread 5s |
| JavaScript | await sleep(5000) | Pause async function, non-blocking |