How to break a loop after a certain elapsed time? I have a function that collects observational data from a user. The user should have a pre-defined time limit, when the data are recorded (30 sec in the example). At the moment, the function breaks, if the user-input arrives later than the end of the time limit.
record.events <- function(duration = 30, first.event = "a"){
# Initial settings
time.start <- proc.time()[3]
events <- c(first.event, 0)
# Timed data collection
while(proc.time()[3] - time.start < duration){
temp <- readline("record events...")
events <- c(events, temp, proc.time()[3] - time.start)
}
# Format recorded data for post-processing
events <- as.data.frame(matrix(events, byrow=T, ncol=2,
dimnames=list(NULL, c("events","stroke.time"))))
events[,2] <- round(as.numeric(as.character(events[,2])),3)
return(events)
}
Gives for example this result:
events stroke.time
1 a 0.000
2 f 2.618
3 a 23.791
4 f 24.781
5 a 33.488
The last event (a) arrived after the time limit. SO has a solution for this in matlab. Is there a way in R, how to stop waiting for the user input as soon as the time is up?
Edit:
While functions setTimeLimit()
and R.utils::withTimeout()
can terminate execution of a function that takes too long (thanks to Kodl, Carl Witthoft and Colombo, together with this answer), neither can interrupt readline()
. Documentation to withTimeout
specifies:
Furthermore, it is not possible to interrupt/break out of a "readline" prompt (e.g. readline() and readLines()) using timeouts; the timeout exception will not be thrown until after the user completes the prompt (i.e. after pressing ENTER).
The user input after the time limit is thus the only way, how to stop waiting for readline
. The check can be executed with the while
loop as in my code, or with setTimeLimit
or withTimeout
in a combination with tryCatch
. I therefore accept Kodl's answer.