Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách dùng setInterval trong JavaScript


Phương thức setInterval() thực thi code lặp lại theo khoảng thời gian (milliseconds).

Cú pháp

setInterval(function, interval_in_milliseconds, param1, param2, ...)
  • function: Function để thực thi.
  • interval_in_milliseconds: Khoảng thời gian giữa các lần chạy.
  • param1, param2...: Tham số truyền cho function (optional).

Ví dụ: Đồng hồ real-time

<!DOCTYPE html>
<html>
  <body>
    <p id="test"></p>
    <script>
      var myVar = setInterval(function() { displayTimer() }, 500);
      function displayTimer() {
        var date = new Date();
        var time = date.toLocaleTimeString();
        document.getElementById("test").innerHTML = "Time: " + time;
      }
    </script>
  </body>
</html>

Quan trọng: Clear Interval

const intervalId = setInterval(() => {
  console.log('Running...');
  if (someCondition) {
    clearInterval(intervalId); // Dừng interval
  }
}, 1000);

setInterval vs setTimeout

Đặc điểmsetIntervalsetTimeout
ChạyLặp lại định kỳChạy một lần sau delay
DriftCó thể drift theo thời gianKhông drift (mỗi lần schedule mới)
PrecisionThấp hơn (callback queue)Cao hơn cho single shot

Pattern: Recursive setTimeout (Precision hơn)

function repeatWithDelay(fn, delay) {
  fn();
  setTimeout(() => repeatWithDelay(fn, delay), delay);
}

// Hoặc async/await
async function repeatAsync(fn, delay) {
  while (true) {
    await fn();
    await new Promise(r => setTimeout(r, delay));
  }
}

Lưu ý

  • Callback chạy trên main thread - tránh heavy computation (block UI). Dùng Web Worker nếu cần.
  • Minimum delay: ~4ms (browser clamping).
  • Tab inactive/background: interval bị throttle (giảm tần suất) để tiết kiệm pin.
  • Luôn lưu intervalId để clearInterval khi không cần (cleanup trong useEffect, beforeunload...).