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

วิธีหยุดการทำงานของ Function ด้วย clearTimeout ใน JavaScript

ใช้ clearTimeout() เพื่อยกเลิก Timer ที่ตั้งไว้ด้วย setTimeout() ก่อนที่จะทำงาน

ตัวอย่างโค้ด: Animation Start/Stop

<html>
  <head>
    <title>JavaScript clearTimeout() method</title>
    <script>
      var imgObj = null;
      var animateId; // เก็บ Timer ID
      
      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';
        animateId = setTimeout(moveRight, 20); // เรียกซ้ำทุก 20ms
      }
      
      function stop() {
        clearTimeout(animateId); // หยุด 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>

คำอธิบาย

  • setTimeout(fn, delay) → คืน Timer ID (Number)
  • clearTimeout(timerId) — ยกเลิก Timer นั้นก่อนทำงาน
  • ต้องเก็บ Timer ID ไว้ใน Variable Scope ที่เข้าถึงได้ (Global/Closure)

ความแตกต่าง clearTimeout vs clearInterval

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

Best Practice: ใช้ requestAnimationFrame แทนสำหรับ Animation

let rafId;
function animate() {
  // update position
  rafId = requestAnimationFrame(animate);
}
function stop() {
  cancelAnimationFrame(rafId);
}

ข้อได้เปรียบ rAF: Sync กับ Browser Refresh Rate (60fps), ใช้ Battery น้อยกว่า, หยุดอัตโนมัติ Tab Inactive