为什么clearInterval不能在一个函数上工作
这是代码
var t = ()=>{ setInterval(()=>{ console.log('hello') },1000) } t(); clearInterval(t)
为什么clearinterval不会阻塞setInterval的执行?
它不能在一个函数上工作,因为这就是机制的devise。 调用setInterval()
返回一个数字,作为呼叫build立的定时器的标识符。 这个数字是必须传递给clearInterval()
。
它不会导致错误传递不是数字的东西,或者传递一个不能识别活动计时器的号码,但呼叫不起作用。
在你的情况下,你的t()
函数可以简单地返回setInterval()
调用的结果,而你的外部代码可以保存,以便稍后使用。
这是因为你需要返回间隔的ID,并清除该ID。
根据文件:
setInterval返回唯一标识时间间隔的间隔标识,以便稍后通过调用clearInterval()将其删除。
//function that keeps logging 'hello' on the console var t = ()=>{ //return the id of the interval return setInterval(()=>{ console.log('hello') },1000) } //get the id of the interval created by the "t" function var id = t(); //alerts the id just to see it alert(id); //clear it - function will stop executing clearInterval(id);
因为你应该为setInterval()引用clearInterval。
var interval = setInterval(); clearInterval(interval);
T不等于setInterval返回值,因为您不会从箭头函数返回值,也不会将其分配给值。
试试这个片段:
var t = ()=> setInterval(()=>{ console.log('hello') },1000) var interval = t(); clearInterval(interval);