Home >Web Front-end >JS Tutorial >How to clear timer in js
#How to clear the timer in js?
Before implementing the clear timer, we need to enable the timer
1. Set the timer
The window object provides Two methods are used to achieve the effect of the timer,
They are window.setTimeout() and window.setInterval. The former can make a piece of code run after a specified time; while the latter can make a piece of code run once every specified time. Their prototypes are as follows:
window.setTimeout(code,millisec);
var i = 0; //设置定时器(循环去执行) var timeId = setInterval(function () { i++; console.log('定时运行:' + i + '次') }, 500) //清理定时器 my$('btn').onclick = function () { window.clearInterval(timeId) }
window.setInterval(code,millisec);
var i = 0; //设置定时器(一次性定时器) var timeId = setTimeout(function () { i++; console.log('定时运行:' + i + '次') }, 500) //清理定时器(这个定时器虽然只有一次,但是也得清理 既可以释放内存,也可以便于后边代码的判断。) my$('btn').onclick = function () { window.clearTimeout(timeId) }
Among them, code can be a piece of code enclosed in quotation marks, or it can be a function name. At the specified time, the system will automatically call the function. When using the function name as the call handle, it cannot contain Any parameter;
When using a string, you can write the parameters to be passed in it. The second parameter in both methods is millisec, which represents the number of milliseconds for delay or repeated execution.
2. Clear the timer
Since the timer will return an integer number when called, this number represents the serial number of the timer, that is, the number of timers timer, so the timer is cleared with the help of this returned number.
Methods for clearing timers: clearTimeout(obj) and clearInterval(obj). (Note that the corresponding timer uses the corresponding clearing method)
The above is the detailed content of How to clear timer in js. For more information, please follow other related articles on the PHP Chinese website!