A question on set interval() and clearinterval()

So i understand how set interval works

I also understand how clear interval works, however im wondering if THIS is possible.

So i could do this

let exampleVariable = setInterval(exampleFunction, 1000)

Then i could do

clearInterval(exampleVariable)

However, in my case my set intervals name is a function and kind of has to be for my code to work. I have this.

Let exampleVariable = () => {setInterval(exampleFunction, 1000)}

Then I try to clearInterval in the same way shown as the variable above and it does not work.

The problem is i need to be able to call that exampleFunction and i cant do that with a variable. Can you not use a named arrow function for clearInterval?

Why not just return the setInterval inside the exampleVariable function. This would allow you to do something like:

let interval = exampleVariable();

When you want to clear the interval you would write:

clearInterval(interval);

Sorry my phone service is super slow and its hard to get a codepen atm but here it is.

So in the real example take a look at the last 2 functions startcountdowntimer and checkforoutoftime, also realized there is a problem with the placing of my call on startcountdowntimer in my renderquiz function causing it to double down on the time decrement. I should be able to fix that though.

You have:

let startCountdownTimer = () => setInterval(decrementCountdown, 1000);

You defined a function that returns the interval, but you never assign the value returned by the function to a variable you could later clear. You wrote:

clearInterval(startCountdownTimer);

but all this does is attempt to clear function and not an interval.

1 Like

I guess I didn’t actually understand clearInterval entirely afterall. I got it to work and learned something new! Thanks once again!