The ordered execution of for loop within Shiny's htmlOutput is not guaranteed

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.

Answer №1

Perhaps this solution could be beneficial:

app:R

   library(shiny)
    library(shinyjs)
    ui <- tagList(
            useShinyjs(),
            fluidPage(
            actionButton("goButton", "Go!"),
            mainPanel(
                     uiOutput("result")
    )))
    server<-  function(input, output) {

            observeEvent(input$goButton, {
                lapply(1:50, function(j){

                        shinyjs::logjs(paste('number=', j))
                    })

            })

    }
    shinyApp(ui = ui, server = server)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to showcase elements[i] from an array using React

I need to cycle through an array of objects and display each item in a component, with the prop being the index number of the array item. This is the snippet of code I have: import React from 'react'; import './projecten.scss'; import ...

Transferring Data from Controller to HTML in AngularJS Version 1

Recently, I started working with angularjs on a new project that involves three main HTML files. The first file is index.html, which contains the ng-view directive. The second file is home.html, where various products are displayed from a database. Each pr ...

Trigger a click event upon page load using jQuery or JavaScript

I tried searching for this functionality on a different website, but it didn't work on my site. Can you help me figure out how to trigger a click event on page load? On one of my pages, a popup box appears when I click on a "project" link. Here is th ...

Waiting for the forEach loop to complete

One of my express endpoints has a functionality that includes checking the availability of domain names against GoDaddy's API. However, I am struggling with how to properly await the results. My code currently iterates through an array called tlds an ...

Inter-service/module communication on a widget interface

We are in the process of creating a widget screen that contains various widgets/modules: Products: Displays a list of products Product Details: Retrieves product details from the server when a selection is made in the "Products" widget. Related Products: ...

What is the best way to iterate through results in a Realm custom resolver function when receiving a response from the

My goal is to develop a function for my custom resolver that retrieves all documents in a collection and updates the payload with new data. The code snippet below illustrates how I am currently getting one client and modifying its information: exports = (i ...

How can I use HTML and Javascript to toggle the visibility of a 'select' element, like a dropdown menu

After adding a dropdown and label within a div, I expected them to hide and unhide when the div is manipulated with a function. However, it seems that this functionality is not working as expected. function ToggleDiv(DivID) { if (document.getElementBy ...

Wait for the scope value to become available before executing the directive or div

I have a unique directive created for SoundCloud that necessitates the SoundCloud URL. The URL is fetched from the database using the $http service, but the issue arises when the div for the directive is loaded before the URL value is defined. The code fo ...

How can I use the jQuery map function to separate IDs with commas?

code: <script> $("#save_other").click(function(e){ e.preventDefault(); question = $(".question:checked").map(function() { return this.id; }).get().join(","); alert(question); ...

Tracking the number of negative values within a group, pausing once a positive value is detected in the most recent observations

Imagine a scenario where we have a data frame structured like this: Month Product sales sales_lag YoY_change chart_color 2021-12-01 Tshirt 82525 108748 -0.2411 Negative 2022-01-01 Tshirt 109411 138472 -0.20 ...

What mistakes am I making in including/injecting functions in AngularJS controllers and factories?

I'm encountering an issue in Angular where I am struggling to inject my factory into my controller. The error message I'm receiving is "Cannot read property 'validar' of undefined". In my project, I have two files - ServiceUtil.js which ...

How to add an hr tag to a div element in HTML dynamically with JavaScript?

Whenever a user interacts with the search box, I have a list that gets populated. Here is an example of the overall structure: <div id="searchResult"> <div> <a href="#">result1</a> </div> <div> <a href="#">result2 ...

Generate - Create 2 different versions of the web application

Currently, I am in the process of learning Grunt and exploring ways to generate 2 variations of an application with different configuration settings. My goal is to have one version where a boolean in a specific .js file is set to false, and another versio ...

Enhancing data processing efficiency in R by circumventing nested loops

In my dataset, I have a contingency table with 6 columns and 37 rows. To perform a correspondence analysis, I need to apply a Chi squared transformation to generate Row profiles and Column profiles. However, I have been advised to use nested loops for the ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

Tips for resolving the 'node-gyp rebuild' problem on Windows 10

While attempting to incorporate a node NPM dependency into my project, I encountered an issue with node-gyp rebuild, which I have already reported. I am aware of a potential solution from this Stack Overflow post, but unfortunately it is not effective for ...

What is the method for including a dynamic image within the 'startAdornment' of MUI's Autocomplete component?

I'm currently utilizing MUI's autocomplete component to showcase some of my objects as recommendations. Everything is functioning correctly, however, I am attempting to include an avatar as a start adornment within the textfield (inside renderInp ...

The string that matches the duration of hour, minute, and second (HMS)

There is a need to extract the digits before h, m, and s into their own groups. The objective is to capture all three groups if possible, but if one or two groups are missing, then the last group(s) should be captured. Currently, the regex /(\d+)(?=h ...

"Looking to trigger a server click using JQuery or Javascript in your code? Here's how you can

I am facing an issue with triggering a Server-Side OnClick event on an ASP Server Button within a User Control using JavaScript or JQuery. The current methods I have tried do not produce the desired result as they do not actually simulate a user clicking t ...

PhantomJS 2.0.0 - Error in Selection: Argument is Not Valid

In the script provided below, there are URLs stored in the "links" array. The function gatherLinks() is designed to collect additional URLs from sitemap.xml based on the URLs present in the "links" array. Once the "links" array reaches a certain number of ...