anvilactual1234
anvilactual1234

Reputation: 33

Stopwatch as input in shiny for R

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

Upvotes: 3

Views: 1074

Answers (1)

Florian
Florian

Reputation: 25405

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)

Upvotes: 8

Related Questions