1: when encapsulating, you can use the timer id as part of the return value, and then clear
2 through clearInterval: encapsulate the method that adds the cleared operation
then you encapsulate a clearInterval method to the same place and call it when you want to clear it.
it is recommended to encapsulate a mySetInterval, to facilitate operation
function mySetInterval(func, delay) {
const id = setInterval(func, delay);
return () => clearInterval(id);
}
const cancel = mySetInterval(func, delay);
cancel();
add a method to your module to clear the timer, and you can call
outs
ide the module.
function destory(){
//...Interval
}
function timer() {
var timeout;
...
var timered = function(){
timeout = setInterval(function() {
...
})
}
timered.cancel = function() {
clearInterval(timeout)
timeout = null
}
return timered
}
because when the previously written setInterval is cleared with clearInterval, the timeout returned by setInterval will be lost. When I do this, I put the timeout push returned by setInterval into the arr array, and determine whether the arr.length is greater than zero before each re-call of setInterval, and call the clearInterval cleanup timer if it is greater than zero.