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ểm | setInterval | setTimeout |
|---|---|---|
| Chạy | Lặp lại định kỳ | Chạy một lần sau delay |
| Drift | Có thể drift theo thời gian | Không drift (mỗi lần schedule mới) |
| Precision | Thấ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đểclearIntervalkhi không cần (cleanup trong useEffect, beforeunload...).