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

Phương thức clearTimeout() & clearInterval() trong JavaScript


Phương thức clearTimeout() xóa bộ hẹn giờ (timeout) đã được thiết lập trước đó bởi hàm setTimeout(). Phương thức clearInterval() xóa khoảng lặp (interval) đã được thiết lập trước đó bởi hàm setInterval().

Dưới đây là mã cho phương thức clearTimeout() và clearInterval():

Ví dụ

<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .timeout { margin-right: 170px; display: inline-block; width: 200px; height: 200px; } .interval { display: inline-block; width: 200px; height: 200px; } .stopTimeout { margin-right: 100px; } </style> </head> <body> <h1>Phương thức clearTimeout() & clearInterval()</h1> <div class="timeout" style="background-color: blue;"></div> <div class="interval" style="background-color: blue;"></div> <br /> <button class="startTimeout" onclick="startTimeout()">BẮT ĐẦU TIMEOUT</button> <button class="stopTimeout" onclick="stopTimeout()">DỪNG TIMEOUT</button> <button class="startInterval" onclick="startInterval()"> BẮT ĐẦU INTERVAL </button> <button class="stopInterval" onclick="stopInterval()">DỪNG INTERVAL</button> <div class="resultInterval"></div> <div class="resultTimeout"></div> <script> let resInterval = document.querySelector(".resultInterval"); let resTimeout = document.querySelector(".resultTimeout"); function changeColor(ele) { if (ele.style.backgroundColor == "blue") { ele.style.backgroundColor = "red"; } else { ele.style.backgroundColor = "blue"; } } let timeout; function startTimeout() { timeout = setTimeout( changeColor.bind(this, document.querySelector(".timeout")), 1500 ); resTimeout.innerHTML = "Timeout đã bắt đầu"; } function stopTimeout() { clearTimeout(timeout); resTimeout.innerHTML = "Timeout đã được xóa"; } let interval; function startInterval() { interval = setInterval( changeColor.bind(this, document.querySelector(".interval")), 1500 ); resInterval.innerHTML = "Interval đã bắt đầu"; } function stopInterval() { clearInterval(interval); resInterval.innerHTML = "Interval đã được xóa"; } </script> </body> </html>

Kết quả

Phương thức clearTimeout() & clearInterval() trong JavaScript

Khi nhấn nút "BẮT ĐẦU TIMEOUT" và "BẮT ĐẦU INTERVAL" và chờ vài giây:

Phương thức clearTimeout() & clearInterval() trong JavaScript

Khi nhấn nút "DỪNG TIMEOUT" và "DỪNG INTERVAL":

Phương thức clearTimeout() & clearInterval() trong JavaScript