Cửa sổ ClearTimeout()
ví dụ 1
Cách ngăn myGreeting() thực thi:
const myTimeout = setTimeout(myGreeting, 3000);
function myGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday to You !!"
}
function myStopFunction() {
clearTimeout(myTimeout);
}
Hãy tự mình thử »Thêm ví dụ dưới đây.
Sự miêu tả
Phương thức clearTimeout()
xóa bộ hẹn giờ bằng phương thức setTimeout()
.
Ghi chú
Để xóa thời gian chờ, hãy sử dụng id được trả về từ setTimeout():
myTimeout = setTimeout( function , milliseconds );
Sau đó, bạn có thể dừng việc thực thi bằng cách gọi clearTimeout():
clearTimeout(myTimeout);
Xem thêm:
Cú pháp
clearTimeout( id_of_settimeout )
Thông số
Parameter | Description |
timeout id | Required. The id returned by the setTimeout() method. |
Giá trị trả về
KHÔNG CÓ |
Thêm ví dụ
Ví dụ này có nút "Bắt đầu" để bắt đầu hẹn giờ, trường nhập cho bộ đếm và nút "Dừng" để dừng bộ hẹn giờ:
<button onclick="startCount()">Start count!</button>
<input type="text" id="demo">
<button onclick="stopCount()">Stop count!</button>
<script>
let counter = 0;
let timeout;
let timer_on = 0;
function timedCount() {
document.getElementById("demo").value = counter;
counter++;
timeout = setTimeout(timedCount, 1000);
}
function startCount() {
if (!timer_on) {
timer_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(timeout);
timer_on = 0;
}
</script>
Hãy tự mình thử »Hỗ trợ trình duyệt
clearTimeout()
được hỗ trợ trong tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |