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!
这是一种可能的方法。我们使用两个reactiveVal,一个用于跟踪剩余时间,另一个用于存储计时器当前是否处于活动状态。
希望这可以帮助!
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1237 次 |
| 最近记录: |