Interrupting readline() after a time interval in R
<p>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.</p>

<pre><code>record.events &lt;- function(duration = 30, first.event = "a"){
    # Initial settings
    time.start &lt;- proc.time()[3]
    events &lt;- c(first.event, 0)

    # Timed data collection
    while(proc.time()[3] - time.start &lt; duration){
        temp &lt;- readline("record events...")
        events &lt;- c(events, temp, proc.time()[3] - time.start)
    }

    # Format recorded data for post-processing
    events &lt;- as.data.frame(matrix(events, byrow=T, ncol=2, 
        dimnames=list(NULL, c("events","stroke.time"))))
    events[,2] &lt;- round(as.numeric(as.character(events[,2])),3)
    return(events)
}
</code></pre>

<p>Gives for example this result:</p>

<pre><code>  events stroke.time
1      a       0.000
2      f       2.618
3      a      23.791
4      f      24.781
5      a      33.488
</code></pre>

<p>The last event (a) arrived after the time limit. SO has a solution for this in <a href="https://stackoverflow.com/questions/34065837/getting-user-input-in-a-time-interval-in-matlab">matlab</a>. Is there a way in R, how to stop waiting for the user input as soon as the time is up?</p>

<h2>Edit:</h2>

<p>While functions <code>setTimeLimit()</code> and <code>R.utils::withTimeout()</code> can terminate execution of a function that takes too long (thanks to <a href="https://stackoverflow.com/users/4999328/kodl">Kodl</a>, <a href="https://stackoverflow.com/users/884372/carl-witthoft">Carl Witthoft</a> and <a href="https://stackoverflow.com/users/4868692/colombo">Colombo</a>, together with this <a href="https://stackoverflow.com/questions/8652681/limiting-the-time-that-a-function-processes-in-an-r-for-loop">answer</a>), neither can interrupt <code>readline()</code>. Documentation to <code>withTimeout</code> specifies:</p>

<blockquote>
  <p>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). </p>
</blockquote>

<p>The user input after the time limit is thus the only way, how to stop waiting for <code>readline</code>. The check can be executed with the <code>while</code> loop as in my code, or with <code>setTimeLimit</code> or <code>withTimeout</code> in a combination with <code>tryCatch</code>. I therefore accept Kodl's answer.</p>