Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript มีฟังก์ชัน sleep() หรือไม่? วิธีหน่วงเวลาการทำงาน

JavaScript ไม่มีฟังก์ชัน sleep() แบบ built-in เช่นภาษาอื่น แต่สามารถสร้างได้โดยใช้ Promise ร่วมกับ setTimeout และใช้ร่วมกับ async/await

ตัวอย่างการสร้างฟังก์ชัน sleep

<!DOCTYPE html>
<html>
  <body>
    <script>
      function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
      
      async function demo() {
        document.write('รอ 5 วินาที!');
        await sleep(5000);
        document.write('ผ่านไป 5 วินาทีแล้ว!');
      }
      
      demo();
    </script>
  </body>
</html>

วิธีใช้งานแบบต่างๆ

1. ใช้กับ async/await (แนะนำ)

async function processData() {
  console.log('เริ่มต้น');
  await sleep(1000);
  console.log('หลัง 1 วินาที');
  await sleep(2000);
  console.log('หลัง 3 วินาทีรวม');
}

2. ใช้กับ Promise chain

sleep(1000)
  .then(() => console.log('หลัง 1 วินาที'))
  .then(() => sleep(2000))
  .then(() => console.log('หลัง 3 วินาทีรวม'));

3. ใช้ในลูป (Loop)

async function countDown() {
  for (let i = 5; i > 0; i--) {
    console.log(i);
    await sleep(1000);
  }
  console.log('เสร็จสิ้น!');
}

ข้อสังเกตสำคัญ

  • sleep ต้องถูกเรียกภายในฟังก์ชัน async เท่านั้น
  • ไม่บล็อก thread หลัก (non-blocking) - โค้ดอื่นยังทำงานต่อได้
  • เหมาะสำหรับการหน่วงเวลาในการ fetch API, animation, หรือ retry logic

รูปแบบสั้นๆ (One-liner)

const sleep = ms => new Promise(r => setTimeout(r, ms));