Component value not updating!

Hello all, I'm trying to create an auto refresh button in my Retool dashboard. So I created a switch to allow turning auto refresh on and off. I added an event handler when the switch changes to run this script:
let i = setInterval(
toTime.setValue(new Date().toUTCString());
if (!autoRefresh.value) {
autoRefresh => the switch component.
toTime => the component that I need to update frequently
interval => text field to enter number of seconds between each update.

it's supposed to keep executing the function as long as autoRefresh is true. when I trigger the event it starts working normally but when I turn the switch off, it doesn't leave the setInterval loop and the loop doesn't recognize the "autoRefresh.value" update. So I can trigger the event but I can't break out of it when I update the switch value.
So how can I manually break out of the setInterval?

If the component is being populated by a query, you can use the following settings:
Screenshot 2022-12-27 at 9.24.16 AM

and then

You can change the Period Interval for the time you need