R: Offer 5 seconds to demand a pause. If no pause demanded, resume the process

542 views Asked by At

How can I offer 5 seconds to the user to write something in order to ask for a pause of indefinite length. If the pause is not demanded within these 5 seconds, the process continues. If a pause is demanded, then the user has all the time (s)he needs and (s)he can hit "enter" in order to resume the process whenever (s)he wants.

The interest of such functionality is that if the user is absent, the pause lasts for 5 seconds only. And if the user is present, then (s)he can enjoy a pause in order to watch the graph that has been produced for example.

The code may eventually look like that:

DoYouWantaPause = function(){
   myprompt = "You have 5 seconds to write the letter <p>. If you don't the process will go on."

   foo = readline(prompt = myprompt, killAfter = 5 Seconds)    # give 5 seconds to the user. If the user enter a letter, then this letter is stored in `foo`.

   if (foo == "p" | foo == "P") {    # if the user has typed "p" or "P"
        foo = readline(prompt = "Press enter when you want to resume the process")  # Offer a pause of indefinite length
   }
}

# Main
for (i in somelist){
    ...
    DoYouWantaPause()
}
1

There are 1 answers

0
Greg Snow On BEST ANSWER

Here is a quick little function based on the tcltk and tcltk2 packages:

library(tcltk)
library(tcltk2)

mywait <- function() {
    tt <- tktoplevel()
    tmp <- tclAfter(5000, function()tkdestroy(tt))
    tkpack( tkbutton(tt, text='Pause', command=function()tclAfterCancel(tmp)))
    tkpack( tkbutton(tt, text='Continue', command=function()tkdestroy(tt)),
        side='bottom')
    tkbind(tt,'<Key>', function()tkdestroy(tt) )

    tkwait.window(tt)
    invisible()
}

Run mywait and a small window will pop-up with 2 buttons, if you don't do anything then after about 5 seconds the window will go away and mywait will return allowing R to continue. If you click on "Continue" at any time then it will return immediately. If you click on "Pause" then the countdown will stop and it will wait for you to click on continue (or pressing an key) before continuing on.

This is an extension of the answer given here.