JavaScript clearTimeout() 和 clearInterval() 方法
javascriptweb developmentobject oriented programming
clearTimeout() 方法清除之前由 setTimeout() 函数设置的超时时间。clearInterval() 方法清除之前由 setInterval() 函数设置的间隔时间。
以下是 clearTimeout() 和 clearInterval() 方法的代码 −
示例
<!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>clearTimeout() & clearInterval() Method</h1> <div class="timeout" style="background-color: blue;"></div> <div class="interval" style="background-color: blue;"></div> <br /> <button class="startTimeout" onclick="startTimeout()">START TIMEOUT</button> <button class="stopTimeout" onclick="stopTimeout()">STOP TIMEOUT</button> <button class="startInterval" onclick="startInterval()"> START INTERVAL </button> <button class="stopInterval" onclick="stopInterval()">STOP 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 has been started"; } function stopTimeout() { clearTimeout(timeout); resTimeout.innerHTML = "Timeout has been cleared"; } let interval; function startInterval() { interval = setInterval( changeColor.bind(this, document.querySelector(".interval")), 1500 ); resInterval.innerHTML = "Interval has been started"; } function stopInterval() { clearInterval(interval); resInterval.innerHTML = "Interval has been cleared"; } </script> </body> </html>
输出
单击"开始超时"和"开始间隔"按钮并等待几秒钟 −
单击"停止超时"和"停止间隔"按钮 −