When using JavaScript for timer operations, sometimes you need to stop executing a specific code segment after a certain period of time, which requires using a timer to terminate the operation. In JavaScript, there are many ways to terminate the timer. Here are some common methods.
Method 1: clearTimeout()
To terminate a single execution timer, we can use the setTimeout() method. When you need to terminate the timer, you can use the clearTimeout() method. For example, the following code will output a message after 5 seconds:
var timer = setTimeout(function() { console.log('任务完成!'); }, 5000);
In this code snippet, setTimeout() calls an anonymous function with 5 seconds as a parameter. This function will be executed once after 5 seconds. We can create a variable timer
for this timer and then use it to call the clearTimeout() method to terminate the timer. For example:
clearTimeout(timer);
The effect of this method is to terminate the timer and prevent the timer from continuing to execute the anonymous function.
Method 2: clearInterval()
If you need to terminate a timer that is executed every once in a while, we can use the setInterval() method. When you need to terminate the timer, you can use the clearInterval() method.
For example, the following code will output a message every 2 seconds:
var interval = setInterval(function() { console.log('任务完成!'); }, 2000);
Similarly, we can create a variable interval
for this timer and then use it to call clearInterval() method to terminate the timer. For example:
clearInterval(interval);
The effect of this method is to terminate the timer of the periodically executed function.
Method 3: Combined with variables to control the timer
In some cases, we may need a more flexible termination timer operation. Therefore, we can combine variables to control the operation of the timer. For example, the following code will output a message every 2 seconds, but only 3 times:
var counter = 0; var interval = setInterval(function() { counter++; console.log('任务完成!'); if(counter == 3) { clearInterval(interval); } }, 2000);
In this example, we use a variable counter
to count when the counter reaches 3 , we called clearInterval() to terminate this timer.
Conclusion
The above are several common ways to terminate the timer. The usage scenarios of each method are slightly different. When you need to terminate a timer that executes once, use the clearTimeout() method; when you need to terminate a timer that executes every once in a while, use the clearInterval() method; when you need a more flexible termination timer operation , which can be achieved by combining variable control timers. It is necessary to choose the appropriate method according to the actual situation.
The above is the detailed content of JavaScript method to terminate timer. For more information, please follow other related articles on the PHP Chinese website!