How to stop a timer when the button is pressed again

Hello, I have this code that turns on a relay for 5 seconds when the button (momentary switch) is pressed and after these 5 seconds turns the relay off. I want the option to turn off the relay before those 5 seconds if I press the button again. Is there any posibility to achieve this? Thank you!

int pinButton = 8;
int Relay = 2;
int stateRelay = LOW;
int stateButton;
int previous = LOW;
long time = 0;
long debounce = 500;
int stayON = 5000; //stay on for 5000 ms
void setup() {
  pinMode(pinButton, INPUT);
  pinMode(Relay, OUTPUT);
void loop() {
  stateButton = digitalRead(pinButton);  
  if(stateButton == HIGH && previous == LOW && millis() - time > debounce) {
    if(stateRelay == HIGH){
      digitalWrite(Relay, LOW);
    } else {
       digitalWrite(Relay, HIGH);
       digitalWrite(Relay, LOW);
    time = millis();
  previous == stateButton;

Not with this in there, no.


All is not lost though, you're already halfway there using millis to do your debounce. You just need to use it to replace the delay too. Check the blink without delay example that comes with the IDE for inspiration.

And, after you look at blink-without-delay, try this:Gammon Forum : Electronics : Microprocessors : State machines