为什么 clearInterval 不适用于函数



这是代码

var t = ()=>{
setInterval(()=>{
console.log('hello')
},1000)

}
t();
clearInterval(t)

为什么清除间隔不阻止 setInterval 的执行?

它不适用于函数,因为这就是机制的设计方式。对setInterval()的调用返回一个数字,该号码充当调用建立的计时器的标识符。这个数字是必须传递给clearInterval()的。

传递不是数字的内容或传递不标识活动计时器的数字不会导致错误,但调用不起作用。

在您的情况下,您的t()函数可以简单地返回setInterval()调用的结果,并且您的外部代码可以保存该结果以供以后根据需要使用。

这是因为您需要返回间隔的 id 并清除该 id。

根据文档:

setInterval 返回一个间隔 ID,该 ID 唯一标识 interval,因此您可以稍后通过调用 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();

}
}

最新更新