Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why clearInterval doesn't work on a function

this is the code

var t = ()=>{

    setInterval(()=>{

        console.log('hello')

    },1000)


}

t();

clearInterval(t)

Why the clearinterval does not block execution of the setInterval?

like image 529
Mark Avatar asked Dec 23 '22 15:12

Mark


1 Answers

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.

like image 189
Pointy Avatar answered Dec 28 '22 10:12

Pointy