Articolours
Articolours

Reputation: 61

Changing output after delay in R Shiny App

I'm trying to get an app which updates it output after a set amount of time (i.e. to make text fade away).

In the example code, I would want "Waiting" to display on the actionButton press, then delay for 5 seconds, then the text changes to "Finished".

For some reason the whole observeEvent executes at once, so the outcome is that there is the actionButton is pressed, then there is a 5 second delay with nothing displayed, then "Finished" displays.

Sorry I don't know how to better explain the issue really - but hoping someone can help. If possible I'd like to stick to just R here, without delving too much into javascript.

library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  textOutput("text"),
  actionButton("press", label = "press")
)

server <- function(input, output) {
  num <- reactiveVal()
  observeEvent(input$press, {
    output$text <- renderText("waiting")
    num(1)
  })

  observe({
    if(!is.null(num())){
      output$text <- renderText({
        Sys.sleep(5)
        "finished"
        })
    }
  })

}

shinyApp(ui = ui, server = server)```

Upvotes: 1

Views: 2123

Answers (1)

Orlando Sabogal
Orlando Sabogal

Reputation: 1630

You can use the delay() function from shinyjs

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  textOutput("text"),
  actionButton("press", label = "press")
)

server <- function(input, output) {
  num <- reactiveVal()
  observeEvent(input$press, {
  output$text <- renderText("waiting")
  delay(5000,
      output$text <- renderText("finished"))
})
}

shinyApp(ui = ui, server = server)

Upvotes: 7

Related Questions