I believe that everyone who has studied our previous two articles has a certain understanding of the principles of JavaScripttimer and the use of timers, then How to clear the timer in JavaScript? Today we will continue to introduce you to the clearing of the timer in JavaScript!
1. There are two types of timers in JS:
window.setTimeout([function],[interval])
Set a timer and set a waiting time[ interval], when the time is reached, the corresponding method [function] is executed. When the method execution is completed, the timer stops (but the timer is still there, but it is useless);
window.setInterval([function],[interval])
Set a timer The timer is set and a waiting time [interval] is set. When the time is reached, the corresponding method [function] is executed. When the method execution is completed, the timer does not stop. It will restart every [interval] in the future. Execute the corresponding method [function] until we manually clear the timer;
2. The timer in JS has a return value:->The return value is a number , represents the current timer number
var timer1=window.setTimeout(function(){},1000); //timer1->1 当前是第一个定时器 var timer2=window.setTimeout(function(){},1000); //timer2->2 当前是第二个定时器 window.clearTimeout(timer1); //->把第一个定时器清除掉,这里也可以用 window.clearInterval(timer1)、 window.clearTimeout(1)、 window.clearInterval(timer1); var timer3=window.setTimeout(function(){},1000); //timer3->3 当前是第三个定时器 ,虽然上面的定时器timer1清除掉了,但是号还是继续往后排的;
3. Clear timer:
window.clearInterval(timer1)/window.clearTimeout(time1);
Both clearing methods can clear the timer set by setTimeout and setInterval (there is a difference between the two methods when setting the timer, but there is no difference when clearing the timer), and the parameter can not only be the timer, but also its return value , such as 1,2; it should be noted that even if the timer is cleared, its return value will not be cleared, and the return value of the timer set later will continue to be arranged backward based on its return value, which is similar When queuing up to get a number at the bank, even if the business on No. 1 is completed, the people behind will continue to get the number from No. 2 instead of starting from No. 1 again;
Summary:
I believe that friends will have their own understanding of timer clearing in JavaScript after studying this article. I hope it will be helpful to your work!
Related recommendations:
The above is the detailed content of Detailed explanation of setting and clearing timers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!