[英]Why clearInterval doesn't work on a function
这是代码
var t = ()=>{
setInterval(()=>{
console.log('hello')
},1000)
}
t();
clearInterval(t)
为什么 clearinterval 不会阻止 setInterval 的执行?
它不适用于某个功能,因为这就是该机制的设计方式。 调用setInterval()
返回一个数字,该数字充当调用建立的计时器的标识符。 该数字是必须传递给clearInterval()
。
传递不是数字的东西或传递不识别活动计时器的数字不会导致错误,但调用无效。
在您的情况下,您的t()
函数可以简单地返回setInterval()
调用的结果,您的外部代码可以保存该结果以供以后随意使用。
这是因为您需要返回间隔的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
因为你应该在 setInterval() 的引用上清除Interval。
var interval = setInterval();
clearInterval(interval);
T 不等于 setInterval 返回值,因为您不从箭头函数返回值,也不将其分配给值。
试试这个片段:
var t = ()=>
setInterval(()=>{
console.log('hello')
},1000)
var interval = t();
clearInterval(interval);
let intervalId = null;
cycle(true);
function cycle(r) {
let myInterval = () => {
return setInterval(() => plusSlides(1), 1000);
}
if (!r) {
clearInterval(intervalId);
} else {
intervalId = myInterval();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.