How to prevent myGreeting() to execute:
const myTimeout = setTimeout(myGreeting, 3000);
function myGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday to You !!"
}
function myStopFunction() {
clearTimeout(myTimeout);
}
Try it Yourself »
More examples below.
The clearTimeout()
method clears a timer set with the setTimeout()
method.
To clear a timeout, use the id returned from setTimeout():
myTimeout = setTimeout(
function,
milliseconds);
Then you can to stop the execution by calling clearTimeout():
clearTimeout(myTimeout);
clearTimeout(
id_of_settimeout)
Parameter | Description |
timeout id | Required. The id returned by the setTimeout() method. |
NONE |
This example has a "Start" button to start a timer, an input field for a counter, and a "Stop" button to stop the timer:
<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>
Try it Yourself »
clearTimeout()
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!