如何在setInterval内部clearInterval
问题:
我遇到了这样的问题:
let callBackFunction = function(timer){
.........
// when i want to clear the TimeInterval:
clearInterval(timer);
};
let timer = setInterval(callBackFunction, 1000 ,timer);
这样会报错: timer变量提前被引用了
solution
实际上, 并不需要按照API中那样刻板的传递参数. 避免参数引用麻烦的解决办法就是在callBack Function中, 直接引用外围的变量, 就是timer, 如下:
let callBackFunction = function(){
.........
// when i want to clear the TimeInterval:
clearInterval(timer);
};
let timer = setInterval(callBackFunction, 1000 ); / / Just don't pass that param