4

这是代码

var t = ()=>{

    setInterval(()=>{

        console.log('hello')

    },1000)


}

t();

clearInterval(t)

为什么 clearinterval 不会阻止 setInterval 的执行?

4

5 回答 5

5

It doesn't work on a function because that's just now how the mechanism was designed. Calls to setInterval() return a number that acts as an identifier for the timer that the call establishes. That number is what has to be passed to clearInterval().

It doesn't cause an error to pass something that's not a number, or to pass a number that doesn't identify an active timer, but the call has no effect.

In your case, your t() function could simply return the result of the setInterval() call, and your outer code can save that for use later however you like.

于 2017-07-21T14:26:46.690 回答
4

It's because you need to return the id of the interval and clear that id.

According to the documentation:

setInterval returns an interval ID which uniquely identifies the interval, so you can remove it later by calling 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);

References

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

于 2017-07-21T14:27:36.437 回答
1

because you should clearInterval on reference for setInterval().

var interval = setInterval();
clearInterval(interval); 
于 2017-07-21T14:27:23.400 回答
0
let intervalId = null;

cycle(true);

function cycle(r) {

    let myInterval = () => {

        return setInterval(() => plusSlides(1), 1000);
    }

    if (!r) {
        clearInterval(intervalId);
      
    } else {
        intervalId = myInterval();
        
    }
}
于 2020-09-03T17:04:27.323 回答
0

T 不等于 setInterval 返回值,因为您不从箭头函数返回值,也不将其分配给值。

试试这个片段:

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

var interval = t();
clearInterval(interval);
于 2017-07-21T14:29:26.407 回答