How to setprogress value by seconds in shiny?


#1

RT, How to set the progress value increment by seconds within observeEvent function?
for example,render a rmarkdown file take 20 seconds, I just want the progress bar incre 5% by 1 second after press some button. anyone give some help for me, thanks very much!

ui.R

ui <- fluidPage(useShinyjs(),
                           actionButton("makefiles", "Make Files",class='btn btn-success',icon("fire")),                                       
                           verbatimTextOutput("total")                    
                )

server.R

server <- function(input, output,session) {
  values <- reactiveValues(i = 0)

  makeFiles <- observeEvent(input$makefiles,{
     withProgress(message = "making......",detail="more than 20s",value=0,{
      #invalidateLater func
      fun <- reactive({
        if(values$i<15){
          invalidateLater(500, session)
          values$i <<- values$i+0.5
        }else{
          return()
        }
      })
      observe({
        invalidateLater(1000, session)
        pg <<- as.numeric(isolate(fun()))
       setProgress(value=pg/14,detail=paste0(pg*7.14,'%'))
        #print(pg)
      })
      #render files
      rmarkdown::render("/srv/shiny-server/rmd/test.Rmd",word_document(),output_file = 'test.docx',output_dir = '/srv/shiny-server/rmd/',quiet=T)
     })
       
  }) 
   output$total <- renderText({
     invalidateLater(1000, session)
     print(isolate(values$i))
   })
}

Can anyone help me?


#2

in the observeEvent function, the invalidLater function must wrapped with observe,but the reactiveValues cannot change the setProgress value immediately,just after rmarkdown::render,the progress bar have closed. I push the R codes take a while. thanks a lot!


#3

I have done it by the javascript, the code like follow:

//accept the total-time from the server.R
Shiny.addCustomMessageHandler('total-time', function(t){
  //console.log('1total-time:'+t);
  setInterval(function (){
  if ($('html').attr('class')=='shiny-busy') {
    setTimeout(function() {
        $('div.busy').show();
    }, 100);
    var progressBar = $('.progress-bar');
    width = 0;
    progressBar.width(width);
    var interval = setInterval(function() {
      width += 100/t;
      width=Math.round(width*100)/100;
      progressBar.css('width', width + '%');
      if (width <= 100) {
        document.getElementsByClassName("progress-detail")[0].innerText=width + '%';
      } else {
        clearInterval(interval);
        width=100;
      }
      //console.log('2total-time:'+t);
      //console.log($('html').attr('class')=='shiny-busy');
    }, 1000);
  } else {
    $('div.busy').hide();
    //clearInterval(interval0);
    //console.log($('html').attr('class')=='shiny-busy');
  }
  
}, 100);

});