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

บทบาทของฟังก์ชัน clearTimeout() ใน JavaScript

clearTimeout() คืออะไร

clearTimeout() ใช้ยกเลิก Timer ที่ตั้งไว้ด้วย setTimeout() ป้องกันไม่ให้ Callback Function ทำงาน

Syntax

clearTimeout(timeoutID);
  • timeoutID: ค่าที่คืนมาจาก setTimeout() (Number)

ตัวอย่างโค้ด (Animation مع Stop)

<html>
<head>
  <title>JavaScript Animation</title>
  <script>
    var imgObj = null;
    var animate;
    function init() {
      imgObj = document.getElementById('myImage');
      imgObj.style.position = 'relative';
      imgObj.style.left = '0px';
    }
    function moveRight() {
      imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
      animate = setTimeout(moveRight, 20); // เรียกตัวเองทุก 20ms
    }
    function stop() {
      clearTimeout(animate); // ยกเลิก Timer
      imgObj.style.left = '0px'; // Reset ตำแหน่ง
    }
    window.onload = init;
  </script>
</head>
<body>
  <form>
    <img id="myImage" src="/images/html.gif" />
    <p>Click the buttons below to handle animation</p>
    <input type="button" value="Start" onclick="moveRight();" />
    <input type="button" value="Stop" onclick="stop();" />
  </form>
</body>
</html>

คำอธิบาย

  1. setTimeout(moveRight, 20) ตั้ง Timer เรียก moveRight อีกครั้งใน 20ms คืนค่า animate (Timer ID)
  2. เมื่อกด Stop เรียก clearTimeout(animate) ยกเลิก Timer ที่รออยู่
  3. Reset ตำแหน่งรูปภาพกลับไป 0px

clearTimeout vs clearInterval

ฟังก์ชัน ใช้กับ พฤติกรรม
clearTimeout(id)setTimeout()ยกเลิกการรันครั้งเดียวในอนาคต
clearInterval(id)setInterval()หยุดการรันซ้ำๆ ตลอดไป

Best Practices

  • เก็บ Timer ID ไว้ใน Variable Scope ที่เข้าถึงได้ (Global หรือ Module Scope)
  • Clear Timeout ก่อน Set ใหม่ เพื่อป้องกัน Multiple Timers:
function debouncedSearch(query) {
  clearTimeout(searchTimeout); // Clear ก่อน
  searchTimeout = setTimeout(() => {
    performSearch(query);
  }, 300);
}

การใช้งานจริง: Debounce, Throttle, Auto-save

// Debounce: รอจน User หยุดพิมพ์
let debounceTimer;
input.addEventListener('input', (e) => {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    searchAPI(e.target.value);
  }, 300);
});

// Auto-save Draft
let saveTimer;
function scheduleSave() {
  clearTimeout(saveTimer);
  saveTimer = setTimeout(saveDraft, 5000);
}

สรุป

clearTimeout() ยกเลิก Timer จาก setTimeout() สำคัญสำหรับ Cleanup, ป้องกัน Memory Leaks, Debounce, Throttle, Animation Control ต้องเก็บ Timer ID ไว้เพื่อ Clear ภายหลัง