且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-15 21:08:34

这是因为您需要返回时间间隔的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