这项工作的代码为什么clearInterval不上的功能
var t =()=>{
setInterval(()=>{
console.log('hello')
},1000)
}
t();
clearInterval(t)
为什么调用clearInterval不会阻止的setInterval的执行?
这项工作的代码为什么clearInterval不上的功能
var t =()=>{
setInterval(()=>{
console.log('hello')
},1000)
}
t();
clearInterval(t)
为什么调用clearInterval不会阻止的setInterval的执行?
它不适用于某个函数,因为那正是该机制的设计方式。拨打setInterval()
的呼叫会返回一个号码,作为呼叫建立的定时器的标识符。这个数字是必须传递给clearInterval()
。
它不会导致错误传递非数字的内容,或传递不能识别活动计时器的号码,但呼叫不起作用。
在你的情况下,你的t()
函数可以简单地返回setInterval()
调用的结果,并且你的外部代码可以保存以供后来使用,只要你喜欢。
因为您应该为setInterval()引用clearInterval。
var interval = setInterval();
clearInterval(interval);
这是因为您需要返回间隔的ID并清除该ID。
根据文档:
的setInterval返回一个间隔ID唯一地标识 间隔,这样就可以通过调用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);
参考
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
T不等于setInterval的返回值,因为你不从你的箭头函数返回一个值,而不要”将它赋值给一个值。
试试这个片段来代替:
var t =()=>
setInterval(()=>{
console.log('hello')
},1000)
var interval = t();
clearInterval(interval);