首页 > 解决方案 > 如何启动和停止 invalidateLater 函数

问题描述

我是 R 和 Shiny 的新手,我想编写一个自动绘图的应用程序,如果我想更改设置,我可以按下停止。我找到了一个简单的例子,当我点击“运行”或“停止”按钮时尝试修改,但没有成功。有人可以展示我的问题或一些我可以学习的文件。谢谢你。

library(shiny)

library(shinyjs)

 shinyApp(

 ui = fluidPage(

      useShinyjs(), 



 # Set up shinyjs

      "Count:", textOutput("number", inline = TRUE), br(),
      actionButton("start", "Start"), br(),
     "The button will be pressed automatically every 3 seconds",br(),
      actionButton("stop", "Stop"), br(),
     "The counter will stop when the button is pressed"
    ),
    server = function(input, output) {
      output$number <- renderText({
        input$start
      })

      observe({
        #if (click("start") == TRUE) {
          click("start")
          invalidateLater(3000)
       # }
      })
      observe({
        click("stop")
        #shinyjs::disable("start")
      })
    }
  )

标签: rshiny

解决方案


解决方案是使用checkboxInput停止按钮:

library(shiny)
library(shinyjs)

shinyApp(

  ui = fluidPage(

    useShinyjs(), 
    # Set up shinyjs

    "Count:", textOutput("number", inline = TRUE), br(),
    actionButton("start", "Start"), br(),
    "The button will be pressed automatically every 3 seconds",br(),
    checkboxInput("stop", "Stop"), br(),
    "The counter is stopped when the checkbox is pressed"
  ),
  server = function(input, output, session) {
    output$number <- renderText({
      input$start
    })

    # unselect stop when start is pressed
    observeEvent(input$start, {
      if(input$stop){
        updateCheckboxInput(session, "stop", value = FALSE)
      }
    })

    # every 3000 ms, press start (if stop is unselected, else do nothing)
    observe({
      invalidateLater(3000)

      if(!isolate(input$stop)){
        click("start")
        updateCheckboxInput(session, "stop", value = FALSE)
      }
    })

    # after clicking start, uncheck stop checkbox
    observeEvent(input$start, {
      updateCheckboxInput(session, "stop", value = FALSE)
    })
  }
)

在此处输入图像描述


推荐阅读