JavaScript Await Dynamic User Input

I have implemented a modified version of a script for generating random numbers in multiple columns of a spreadsheet, inspired by Tim Cooper's solution on stackoverflow. This script works by selecting a range of cells and running it from an onOpen menu.

My customized function, built into Google Sheets, uses the values from column A as maximum values for generating random numbers in column B. The generated numbers are then used to calculate subsequent input values. Here is a simplified example:

The function reads A1 and generates a random number between 0 and A1 (80) in B1. Subsequently, A2 is calculated by adding 10 to B1, and so on.

     |  A  |  B  |
  1  | 80  | 75  |
  2  | 85  | 63  |
  3  | 73  | 52  |
  4  | 62  | 40  |
  5  | 50  | 25  |

However, I am facing an issue where the spreadsheet takes some time to fill in the next input value (such as A2), leading to errors when the custom function needs the input promptly to generate the next random value.

The current custom function is a single block of code that identifies the active sheet and cell range, loops through each row to retrieve input values, calculates random values based on the specified maximums, and writes them to adjacent cells.

function generate_random_numbers()
{
  var sheet = SpreadsheetApp.getActiveSheet()
  var range = sheet.getActiveRange()
  var counter = 0

  for (var y = 1; y <= range.getHeight(); y++)
  {
   counter = counter + 1
   if (counter != 3)
   {
    var maximum = range.getCell(y, 1).getValue()
    var random = (maximum != 0) ? Math.floor(Math.random() * maximum) + 1: 0
   }
    else
   {
    random = ""
    counter = 0
   }
   range.getCell(y, 2).setValue(random)
  }
}

To address this delay issue, I considered splitting the function to handle value retrieval separately, checking for isNaN to confirm success and using setTimeout to pause the function for 100 milliseconds in case of failure. However, Google Apps Script does not seem to support setTimeout functionality.

If anyone has suggestions on improving the interaction between a dynamic value-based spreadsheet and a script to ensure smooth operation, I would greatly appreciate it.

Answer №1

The main issue lies within Google Apps Script's cache system, specifically the look-ahead caching feature that restricts custom functions to only using values present in the spreadsheet when the function was initially called.

One potential solution is to utilize SpreadsheetApp.flush() to manually update the cache by writing newly calculated values from the custom function back into the spreadsheet and then reading these updated values back into the cache. However, this method can be slow and may result in some cells displaying "Loading..." due to the continuous updating required to keep the cache current.

To address this challenge, I opted to transition all calculations from the spreadsheet to custom functions. Although it required a learning curve, this approach proved to be much faster and more stable than relying on the built-in caching mechanism. By storing values in global arrays organized by specific categories and isolating calculations within dedicated functions, maintenance and adjustments became significantly easier.

Despite not resolving the core issue directly, but rather working around it, I decided to report the problem on Google's Apps Script Issues and Requests page, following a suggestion from Sandy.

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

Is it possible to integrate a jQuery function within PHP code when encountering a "is not defined"

I am looking to implement the jQuery-confirm dialog in place of using a JavaScript alert generated by PHP. However, when I execute the following code, I encounter the following error message: $ is not defined echo "<script>$.alert({title: ' ...

How can JavaScript determine if this is a legitimate JS class?

I'm currently in the process of converting a React.js project to a next.js project. In my project, there's a file named udf-compatible-datafeed.js. import * as tslib_1 from "tslib"; import { UDFCompatibleDatafeedBase } from "./udf-compatibl ...

Attempting to assign a thumbnail image to a file on Google Drive by utilizing JavaScript

I've been working on adding thumbnails to the files that I upload to Google Drive using Javascript. I'm following the instructions outlined at https://developers.google.com/drive/v3/web/file#uploading_thumbnails For my web-safe base64 image, I c ...

The issue with jqTransform not displaying the select box value on a hidden contact form

Could really use some assistance here and apologize if it's a hassle: Link to contact form To view the contact form, simply click the "Contact" button in the top left corner. The jqTransform jQuery plugin is being used to style it. Initially, it&apo ...

Executing a function after an AngularJS directive's reference function has been called

<CustomDirective customValue="someValue" anotherFunctionRef="anotherFunction()"></CustomDirective> angular.module('AppName', ['OtherDependencies']). directive('CustomDirective', ...

Add the Selected Value to the Title

Is there a way to dynamically add the selected value from each select element to its corresponding heading without requiring user interaction? I need this to happen as soon as the page loads. Here is an example in a jsfiddle https://jsfiddle.net/dqfvyvdt/2 ...

Ensure each list item is directly aligned when swiping on a mobile device

Looking to make a simple horizontal list swipeable on mobile devices with tabs that snap from tab to tab, activating the content for the active tab immediately. The desired effect is to swipe directly from one tab to the next without having to click separ ...

It appears that the JavaScript global dynamic variable is undefined as it changes from function to function, suggesting it might be

I'm encountering an issue with the way these two functions interact when used in onclick calls of elements. Due to external circumstances beyond my control, I need to keep track of when and how elements are hidden. Everything works perfectly as inten ...

Awaiting fulfillment - Promise remains pending as loop executes queries

I have a scenario where I receive an array containing multiple data elements and need to perform a query for each element in the array. However, this is resulting in a promise pending response. How can I resolve this issue? What could be causing it? getFa ...

How can I correctly connect a JavaScript library that has been installed via npm?

After using npm to install a JS library, such as: npm install chartjs The necessary JS file is typically located at ./node_modules/chartjs/chart.js. If you prefer the file to be in a different location, like ./public/js/chart.js, you could manually m ...

The issue of a non-firing Ajax click event in a JavaScript file

I have set up a table in JSP and am attempting to trigger a function when clicking on the table rows to post the data. I created a JavaScript file with an ajax click event, but unfortunately, the event is not being fired. $(document).ready(function( ...

Pushing items to an array is causing the loss of previously added data

Currently, I am working on developing a prototype of a Restaurants application using Angular 8. In this project, I have implemented @Input() to transfer individual restaurant data as an object from the parent component to the RestaurantCardComponent for pr ...

Navigating with buttons in React JS

In my material-ui, I have a button set up like this: <Button style={green} raised="true" label="Continue to create group"}> CREATE NEW GROUP </Button> I am looking to make it so that when the button is clicked, it will take me ...

Unable to dynamically translate special characters using npm latinize

When translating German special characters to English using latinize, the module only works when strings are passed within single or double quotes. However, it does not work when storing them inside a variable. import latinize from 'latinize'; ...

The response from a jQuery ajax call to an MVC action method returned empty

I am working on an inventory application with the following layout: <body> <div class="container" style="width: 100%"> <div id="header"> blahblahblah </div> <div class="row"> <div id="rendermenu ...

Executing both JavaScript Promise .then() and .catch concurrently

I've been working on converting my WordPress comments into an ajax-driven system. Everything was going smoothly until I encountered a problem with the .catch() method triggering right after the .then() method. Below is the code snippet... Ajax engi ...

JavaScript's getElementsByName() method allows for easy access and

Excuse my lack of experience... I am attempting to run a javascript using the getElementByName method, with the goal of entering 0 in the quantity field on a particular site after 15 seconds of arriving there. Upon inspecting the quantity field, here is w ...

What causes the React Query cache to be cleared upon page reload?

Hi there, I am new to Next.js and React Query. I would really appreciate any help or advice. I apologize for any mistakes in my English language skills. Currently, I am using Next.js v12 and React Query v3, along with the React Query DevTools. On one of ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Looking to retrieve the mouse coordinates using JavaScript

How can I use JavaScript to track the mouse position on a canvas? Upon visiting this page: http://billmill.org/static/canvastutorial/mouse.html They provide this code snippet: function initializeMouse() { canvasMinimumX = $("#canvas").offset().left; ...