Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a countdown timer in Shiny?

Tags:

r

shiny

I'd like to be able to create a countdown timer (example: 20 minutes and then the timer beeps) for an R Shiny app that I'm working on that the user can start, stop, and reset by clicking start/stop/reset buttons. I've seen a few examples of countdowns that count towards a specific date/time, but haven't come across one for a generic timer. Is something like this possible? Any help would be appreciated!

like image 874
rossdrucker9 Avatar asked Mar 13 '18 07:03

rossdrucker9


1 Answers

Here is one possible approach. We use two reactiveVal's, one to keep track of the time left, and one to store if the timer is currently active or not.

Hope this helps!


enter image description here


library(lubridate)
library(shiny)

ui <- fluidPage(
  hr(),
  actionButton('start','Start'),
  actionButton('stop','Stop'),
  actionButton('reset','Reset'),
  numericInput('seconds','Seconds:',value=10,min=0,max=99999,step=1),
  textOutput('timeleft')

)

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

  # Initialize the timer, 10 seconds, not active.
  timer <- reactiveVal(10)
  active <- reactiveVal(FALSE)

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

  # observer that invalidates every second. If timer is active, decrease by one.
  observe({
    invalidateLater(1000, session)
    isolate({
      if(active())
      {
        timer(timer()-1)
        if(timer()<1)
        {
          active(FALSE)
          showModal(modalDialog(
            title = "Important message",
            "Countdown completed!"
          ))
        }
      }
    })
  })

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

}

shinyApp(ui, server)
like image 72
Florian Avatar answered Oct 03 '22 08:10

Florian