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

หยุดการทำงานของ Function ระหว่างรันใน JavaScript

ใช้ setInterval รัน Function ซ้ำ และ clearInterval หยุดการทำงาน

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stop Function</title>
</head>
<body>
  <button type="button" id="call">Call the function</button>
  <button type="button" id="halt">Stop the function execution</button>
  <script>
    document.getElementById("call").addEventListener("click", callFunction);
    document.getElementById("halt").addEventListener("click", haltFunction);
    
    let timeValue = null;
    
    function callFunction() {
      timeValue = setInterval(() => {
        console.log("The call() is being executed....");
      }, 1000);
    }
    
    function haltFunction() {
      clearInterval(timeValue);
      console.log("Function stopped");
    }
  </script>
</body>
</html>

คำอธิบาย

  • setInterval(fn, 1000) เรียก fn ทุก 1 วินาที คืน Interval ID
  • clearInterval(id) หยุด Interval นั้น
  • ตัวแปร timeValue ต้องเป็น Global/Closure Scope เพื่อเข้าถึงได้จากฟังก์ชันหยุด
  • สำหรับ setTimeout ใช้ clearTimeout(id)
  • Pattern นี้ใช้สำหรับ: Polling, Animation, Auto-save, Real-time Updates

ผลลัพธ์

กด "Call" → Console Log ทุก 1 วิ | กด "Stop" → หยุด Log ทันที