Exit function after specified time

Hi,

Im not sure if someone already asked this before, but I was wondering if I could break from a function if the function doesn't fully execute in say 6 seconds.

Basically this is the function which will be running to calculate the time it takes a magnet to pass once over a reed switch:

void tripuino::rech(unsigned long *timestart, unsigned long *timeend){
    while (digitalRead(3) == HIGH){
    }
    *timestart = millis();
    while (digitalRead(3) == LOW){
    }
    while (digitalRead(3) == HIGH){
    }
    *timeend = millis();
}

I want the function to stop executing if it takes longer than six seconds to indicate that the speed is roughly zero in the rest of my code. Would I need to use an interrupt or is there another way of achieving my goal?

Thanks in advance

You should move timestart declaration before the first while loop. Then, in each while loop, check the condition AND check that now (millis()) minus the start time is less than 6 seconds.