Reputation: 23
I apologyse in advance if the question is a bit unclear!
I created a for-loop that generates a plot every 0.1 seconds (to simulate a video of a moving object). The code works smoothly, but I would like to allow the user to pause and resume the "video" when he/she wants to inspect in more detail one of the video frames.
I thought about reading an input from the console using readline() or scan() functions at the end of the loop. For example, the user types "p"+enter to pause the video. However, readline() would expect an input at the end of each iteration. In my case, the user would only provide an input in some of the iterations, so the loop must continue running when no input is given.
This would be a simplified version of the loop (printing a value in the console instead of plotting an image):
for(index in c(1:10)){
print(index) # In my script it generates a plot
Sys.sleep(0.1)
input = read.line() # If user types an input in the command, execution is paused
# If no input is given, the loops continues with the next iteration
...
...
}
Do you have any ideas/suggestions of how to deal with this? Thanks :)
Upvotes: 2
Views: 369
Reputation: 31452
Something like this using library(shiny)
to provide a pause/resume button could work:
ui = fluidPage(
actionButton("pause", "Pause"),
plotOutput("myplot")
)
server = function(input, output, session) {
rv <- reactiveValues(i = 0, go = TRUE)
maxIter = 1000
timer = reactiveTimer(100)
output$myplot = renderPlot({
x = seq_len(1000)
y = sin(x/20 + rv$i) * cos(x/50 + rv$i/2)
plot(x, y, type = "l", main = rv$i, ylim = c(-1,1))
})
observeEvent(input$pause, {
rv$go = !rv$go
updateActionButton(session, inputId = "pause",
label = c("Resume", "Pause")[rv$go + 1L])
})
observeEvent(timer(), {
req(rv$i < maxIter)
req(rv$go)
rv$i = rv$i + 1
})
}
shinyApp(ui = ui, server = server)
Upvotes: 1