为什么clearInterval在函数上不起作用

为什么clearInterval在函数上不起作用

问题描述:

这是代码

var t = ()=>{

    setInterval(()=>{

        console.log('hello')

    },1000)


}

t();

clearInterval(t)

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

Why the clearinterval does not block execution of the setInterval?

这是因为您需要返回时间间隔的ID并清除该ID.

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

根据文档:

setInterval返回一个间隔ID,该ID唯一地标识 时间间隔,因此您可以稍后通过调用clearInterval()将其删除.

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);

参考

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