Is there a way to create a timer?

I would like to create a timer where I set a GPIO and then x minutes later, reset that GPIO. This doesn’t need to be accurate and x needs to be 10 minutes max. I’ve tried some of the imp objects (https://electricimp.com/docs/api/imp/) but I would like to stop this timer via a button I have connected to the board or possibly by sending a command to the board through agent code. Right now I’m using a while loop (as shown in the code below) that can detect a button press and stop, but the device loses connection inside this loop if it’s longer than 2 minutes so I would like another method. Any ideas? Thanks.
while (hardware.millis() < stopTime){ // let pressing the button cancel the timer if (button.read() == 1) { // button has been pressed while (button.read() == 1) {} // wait til button has been released imp.sleep(0.2); // delay by 200ms to prevent debounce server.log("Timer interrupted by button"); break; } }

I would set a timer using imp.wakeup(). Remember, this method returns a reference to the timer, which can be cancelled:

timer <- imp.wakeup(600.0, resetGPIOFunction)

This will call your resetGPIOFunction() in 10 mins. If the button gets pushed in the meantime, then just cancel the timer:

imp.cancelwakeup(timer)

BTW, there’s a good Squirrel class for dealing with debouncing in buttons here.

Thanks! I thought I tried that before but after your explanation, I got it working. For others’ reference, here is my new timer code using imp.wakeup()

`// function to find out when the relay will turn off, then start timer
// and assign the button to stop timer
function setTimer(numberCups) {
// convert numberCups to an amount of time in seconds
onTime = (2.5 + numberCups) * min2sec
server.log(“Set relay timer for " + onTime/min2sec + " minutes”)
// configure button to turn off during timer
button.configure(DIGITAL_IN_PULLDOWN, cancelTimerByButton)
// turn relay on
relay.write(1)
// create timer
timer <- imp.wakeup(onTime, turnOffRelay)
}

// function to turn off relay and cancel timer if button is pressed during timer
function cancelTimerByButton(){
if (button.read() == 1) { // button has been pressed
while (button.read() == 1) {} // wait til button has been released
// cancel timer
imp.cancelwakeup(timer)
// turn off relay
relay.write(0)
server.log(“Timer interrupted by button; relay is now off”)
// set button back to normal operation
button.configure(DIGITAL_IN_PULLDOWN, toggleRelay)
}
}

// function to turn off relay from timer function
function turnOffRelay() {
// turn off relay
relay.write(0)
server.log(“Timer is over; relay is now off”)
// set button back to normal operation
button.configure(DIGITAL_IN_PULLDOWN, toggleRelay)
}
`

Splendid! Glad to hear you got it sorted, @Dillon1337