You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny开发中Waiter包加载条执行完成后无法正常消失问题求助

Waiter包Waitress进度条执行完成后残留白框的解决方案

问题根因

  • Waitress实例在server全局作用域初始化,多次点击按钮会生成多个重叠实例,调用close()仅能销毁最新实例,旧实例生成的DOM元素会残留
  • 未显式指定进度条挂载容器,默认生成的全局遮罩元素关闭时无法被完全清理

修改方案

调整Waitress实例的创建逻辑,将实例化操作放到按钮点击的响应事件内部,同时绑定进度条到绘图输出区域,用完直接销毁实例即可解决残留问题。
修改后的完整可运行代码如下:

library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(waiter)

new_choices <- setNames(names(mtcars), names(mtcars))


ui <- fluidPage(
  # Application title
  titlePanel("My shiny app"),
  sidebarLayout(
    sidebarPanel(
      tabsetPanel(
        tabPanel("Selection",
                 selectInput("x_axis", "Choose x axis",
                             choices = new_choices),
                 selectInput("y_axis", "Choose y axis",
                             choices = new_choices),
                 hr(),
        ),
        tabPanel("Titles",
                 hr(),
                 textInput(inputId = "title", "You can write the title:",  value = "This is the title"),
                 textInput(inputId = "xlab", "You can re-name the x-axis:",  value = "x-axis...."),
                 textInput(inputId = "ylab", "You can re-name the y-axis:",  value = "y-axis ...."),
        ),
        tabPanel("Calculations", 
                 hr(),
                 checkboxInput("log2", "Do the log2 transformation", value = F),
                 checkboxInput("sqrt", "Calculate the square root", value = F),
        )
      ),
      useWaitress(),
      actionButton(inputId = "drawplot", label = "Show the plot")
    ),
    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("plot"),
    )
  )
)


server <- function(input, output, session) {
  data <- reactive({
    mtcars
  })
  
  filtered_data <- reactive({
    data <- data()
    if(input$log2 == TRUE){
      data <- log2(data+1)
    }
    if(input$sqrt == TRUE){
      data <- sqrt(data)
    }
    return(data)
  })
  
  v <- reactiveValues()
  observeEvent(input$drawplot, {
    # 每次点击新建实例,绑定到绘图输出区域#plot,避免全局残留
    waitress <- Waitress$new(theme = "overlay-percent", min = 0, max = 10, container = "#plot")
    # 启动进度提示
    waitress$notify()
    
    for(i in 1:10){
      waitress$inc(1) # increase by 10%
      Sys.sleep(.3)
    }
    
    v$plot <- ggplot() +
      geom_point(data = filtered_data(),
                 aes_string(x = input$x_axis, y = input$y_axis)) +
      xlab(input$xlab) +
      ylab(input$ylab) +
      ggtitle(input$title)
    
    # 关闭并销毁实例,彻底清理DOM元素
    waitress$close()
    waitress$destroy()
  })
  
  output$plot <- renderPlot({
    if (is.null(v$plot)) return()
    v$plot
  })
}

shinyApp(ui, server)

内容的提问来源于stack exchange,提问作者emr2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:45:03