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!
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With