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

如何在Shiny应用中使用自定义GIF作为加载动画并实现闲置时隐藏?

解决Shiny中自定义GIF加载动画不自动消失的问题

方法1:用withBusyIndicatorServer自动控制状态

将耗时操作包裹在withBusyIndicatorServer中,它会自动在任务开始时显示GIF,结束时隐藏。

修改后的完整代码:

library(shiny)
library(shinybusy)

ui <- fluidPage(
  add_busy_gif(
    src = "https://jeroen.github.io/images/banana.gif",
    height = "70px", width = "70px", position = "bottom-right"
  ),
  actionButton("sleep", "Long calculation")
)

server <- function(input, output, session) {
  observeEvent(input$sleep, {
    withBusyIndicatorServer("sleep", { # 绑定触发按钮的ID
      Sys.sleep(5)
    })
  })
}

shinyApp(ui, server)

方法2:手动调用显示/隐藏函数

如果需要更灵活的控制逻辑,可直接用show_busy_gif()和hide_busy_gif()手动切换GIF状态:

library(shiny)
library(shinybusy)

ui <- fluidPage(
  add_busy_gif(
    src = "https://jeroen.github.io/images/banana.gif",
    height = "70px", width = "70px", position = "bottom-right"
  ),
  actionButton("sleep", "Long calculation")
)

server <- function(input, output, session) {
  observeEvent(input$sleep, {
    show_busy_gif() # 任务开始时显示GIF
    on.exit(hide_busy_gif()) # 确保任务结束/出错时都隐藏GIF
    Sys.sleep(5)
  })
}

shinyApp(ui, server)

问题原因

原代码中Sys.sleep(5)属于简单阻塞操作,shinybusy的自动状态检测无法精准捕捉。通过上述两种方式,我们明确指定了繁忙状态的起止时机,从而让GIF正确显示和消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:18:17