3

Is there a possibility of having a visible stopwatch (startable and stoppable) in an R shiny app, of which the amount of seconds could be used as an input value?

I do not know of any implementations. Is there a simple way to do this? Thanks for your answer in advance

  • 1
    The chances of someone answering your question in the future will be much higher if you show some research effort, what have you tried yourself, and where did you get stuck or why did your attempt fail? See also [here](https://stackoverflow.com/help/how-to-ask). – Florian Jul 20 '18 at 07:16

1 Answers1

7

Here is one possible solution, adapted from my answer here for a countdown timer.

Hope this helps!


enter image description here


library(lubridate)
library(shiny)

ui <- fluidPage(
  hr(),
  actionButton('start','Start'),
  actionButton('stop','Stop'),
  actionButton('reset','Reset'),
  tags$hr(),
  textOutput('timeleft')

)

server <- function(input, output, session) {

  # Initialize the timer, not active.
  timer <- reactiveVal(0)
  active <- reactiveVal(FALSE)
  update_interval = 0.1 # How many seconds between timer updates?

  # Output the time left.
  output$timeleft <- renderText({
    paste("Time passed: ", seconds_to_period(timer()))
  })

  # observer that invalidates every second. If timer is active, decrease by one.
  observe({
    invalidateLater(100, session)
    isolate({
      if(active())
      {
        timer(round(timer()+update_interval,2))
      }
    })
  })

  # observers for actionbuttons
  observeEvent(input$start, {active(TRUE)})
  observeEvent(input$stop, {active(FALSE)})
  observeEvent(input$reset, {timer(0)})

}

shinyApp(ui, server)
Florian
  • 24,425
  • 4
  • 49
  • 80
  • So neat! Is that possible to adapt the same idea for showing how fast the code is running? E.g. there's a `very_slow_function<-function()` and I want an indicator in my Shiny App in secs while this `very_slow_function` is running ? (So I know that computer did not freeze, but is actually doing something) – IVIM Oct 20 '21 at 13:23