I've encountered a peculiar situation while working with loops inside a Shiny htmlOutput. My objective was quite straightforward - to execute a JavaScript code (console.log) from the Shiny htmlOuput and print the loop number to the console. Check out the code snippet below:
library(shiny)
ui <- fluidPage(
actionButton("goButton", "Go!"),
mainPanel(htmlOutput("result"))
)
server<- function(input, output) {
observeEvent(input$goButton,{
output$result <- renderUI({
html_output_list <- lapply(1:50, function(j) {
htmlname <- paste("html", j, sep="")
htmlOutput(htmlname)
})
do.call(tagList, html_output_list)
})
lapply(1:14, function(i){
htmlname <- paste("html", i, sep="")
output[[htmlname]] <- reactive({
paste('<script>number=',
i,
';console.log(number);</script>')
})
})
})
}
shinyApp(ui = ui, server = server)
When you click the go button, the expected result should be an ordered sequence of numbers ranging from 1 to 14 (as the number 'i' loops from 1 to 14). However, the actual outcome is 14,1,2,...,13. Changing the range of 'i' to 1:20 produces a sequence like (14,15,16,17,18,1,19,2,3,4,5,6,7,8,20,9,10,11,12,13). Can anyone shed light on what's happening here? Why isn't it following the order as expected? It's definitely not random.