Verify whether the function is operational using Google Apps Script and Google Web Apps

I have created a basic Google Apps Script that links to IFTTT on my phone and sends SMS messages. Now, I am attempting to create a more user-friendly interface by deploying the script as a Google Web App. The concept is simple: click a button, see "Sending SMS," and wait until the process is completed.

I believe the button code needs to check if the script is running or not (i.e., terminated), but I am struggling to make it work.
Here is how I have set things up:

In code.gs, I have the main function responsible for sending SMS messages:

var isRunning;
function execute() {
 isRunning = true;
 if (checkRunning() == true) {Logger.log('isRunning: TRUE')} else {Logger.log('isRunning: FALSE')}
 OTHER STUFF;
 isRunning = false;
 if (checkRunning() == true) {Logger.log('isRunning: TRUE')} else {Logger.log('isRunning: FALSE')}
}

and the function that checks whether the variable isRunning is true or false:

function checkRunning() {
  if (isRunning == true) {
    return true}
    else {return false}
}

In my index.html file, there is a button to run the script and another to check its status:

<input class="button" type="button" value="Send SMS" onclick="google.script.run.execute()"/>
<input class="btncheck" type="button" value="Check running"/>

with this code within the <script></script> tags (using Jquery):

var c;
setInterval(function() {
  google.script.run.withSuccessHandler(varSet).checkRunning()
},1000);
function varSet(value) {c = value}

$('.btncheck').on('click', function() {
   alert();
 }); 

function alert() {
   alert(c)
}

I know that the execute() function runs for approximately 15 seconds. So, if I click the "Execute" button, I should be able to click the "Check running" button shortly after and receive a response of true. However, it always displays false because the checkRunning() function returns false.
In the script Log, though, the isRunning variable is correctly set to true at the start and false at the end of execute().
Any suggestions?

Answer №1

I believe that with each client-to-server call, a new execution context is created. This means that variables cannot be persisted between function calls unless they are saved to a 'stable' object like a spreadsheet or file. Since google.script.run calls are asynchronous, they have different instances of the global object from the .gs file, causing the "checkRunning()" function to be isolated in its own execution context without access to or communication with parallel threads.

To overcome this restriction, CacheService can be used to persist data and eliminate the need for global variables entirely. I successfully implemented this by making the following modifications:

function setIsRunning(value){

  CacheService.getScriptCache().put("isRunning", value.toString());

}

function execute() {

 setIsRunning(true);

  Utilities.sleep(15000); // simulate execution for 15 seconds

 setIsRunning(false);

}


function checkRunning() {

var currentState = CacheService.getScriptCache().get("isRunning");

 return (currentState == 'true');
}

It's important to note that returning (currentState == 'true') converts the String to Boolean. For example, Boolean('false') will result in true.

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

Vue JS - Show validation error message for checkboxes upon submission

I am encountering an issue with my registration form. I have a checkbox that needs to be validated when the submit button is clicked. The problem is, the validation error appears immediately because the checkbox starts off unselected. I would like the vali ...

Avoiding unnecessary Ajax requests using pushstate for pagination

I encountered an issue with ajax pagination using the HTML API Pushstate. Here is the code I am working with: <ul class="small"> <li> <p>a</p> </li> </ul> <ul class="paging"> <li><a ...

Issue encountered when attempting to alter the action attribute of a form: receiving an error message stating 'undefined is not a function'

I am attempting to dynamically set the action attribute of a form based on the button clicked in order to navigate away from a page. Once the action is updated, the form should be submitted and the new action carried out. Below is my jQuery function: fun ...

React JS functionality does not support Bootstrap tooltips

I'm attempting to implement a tooltip in my React app, but I'm experiencing issues with it not displaying properly. I am utilizing vanilla Bootstrap for this purpose. I've included the following script tag in my index.html file to import the ...

Updating text in React Native does not reflect changes in context after a state change

I'm facing a challenging issue that I just can't seem to figure out. Here's the dilemma: <TouchableOpacity onPress={() => { if (myContext.value) { alert('true'); //changes myContext.value to false } els ...

Guide on organizing users into groups and filtering them using Firestore's reference field type

I currently manage a small group of employees with plans to expand in the future. To streamline operations, I am looking to implement a grouping feature that allows users to sort employees based on their assigned groups. Although I thought about using the ...

Generating email expiration tokens without relying on a database or utilizing crontab for automatic deletion

My API server has an authentication system using JWT tokens for registration, login, and forgotten password functionality. When a user forgets their password, they receive an email with a unique token and link to reset it. Currently, I generate a UUID to ...

Unable to execute PHP files using Node.js

I have been working on a Node.js web application hosted on a Heroku server. The issue I am facing is related to an AJAX request in my JavaScript code that sends a GET request to a PHP file on the server. Interestingly, this request works perfectly when I r ...

Implement AJAX and PHP to submit form data along with the page ID and session information

I am currently developing a school book library website project that allows students to browse and select books, as well as send requests to the librarian to borrow them. However, I am still learning jQuery and facing some challenges in handling issues. H ...

Issues arise when building with Angular using `ng build`, but everything runs smoothly when using `

My Angular 5 application uses angular-cli 1.6.8 { "name": "test", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "karma": "ng test", "test": "jest", "test:watch": "j ...

The scrolling event on the div is not triggering

I'm struggling with this piece of code: const listElm = document.querySelector('#infinite-list'); listElm.addEventListener('scroll', e => { if(listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) { th ...

Is it possible to reset the selectbox after removing options using Javascript/jQuery?

When I run the command below in a loop: $("#day option:last").remove(); If this command is executed multiple times, some options are missing from my selectbox. Therefore, I am looking for a way to reset the selectbox back to its original state at the be ...

Refreshing Angular 7 application does not function properly on IIS despite having the web.config properly set up

Something strange is happening with my Angular 7 application. Whenever I click refresh, the routes seem to be lost and a 404 error is displayed. Despite following advice to configure the web.config file, this behavior persists. Here's a snippet from ...

Retrieving latitude and longitude coordinates to determine percentage-based or pixel-based x and y positions

I'm currently working on extracting percentage or pixel coordinates from a latlng in leaflet maps. Here is the code snippet that sets up the map and tile layers (adapted from an app named 'maptiler') var mapMinZoom = 0; var mapMaxZ ...

Steps to toggle text color upon clicking and switch the color of another text

As a beginner with no Js knowledge, I am trying to achieve a specific function. I want to be able to change the color of text when it is clicked, but also have the previously clicked text return to its original color. <div class="mt-5 fi ...

Encountered a VUE error stating "Cannot use 'in' operator to search for 'path' in undefined". This issue led to an infinite loop, prompting me to search for solutions on StackOverflow and other similar forums. More details can be found

I am currently using this demo for learning purposes. If you want to see the full code, you can visit my GitHub repository here: https://github.com/tNhanDerivative/nhanStore_frontEnd and access my domain: vuestore.nhan-thenoobmaster.com. The error I am exp ...

Behat automates the process of populating form fields that are dynamically displayed as 'visible'

I'm facing an issue with a form that has hidden fields. When a user selects a checkbox, some of the hidden form fields are supposed to be revealed using the jQuery function slideToggle(). The code itself is pretty simple and you can see an example her ...

Using JavaScript to extract data from JSON with differing value types

Struggling to format a String by parsing a JSON object. Here's an example of the data I'm working with: { "age": 35, "name": "", "time": { "24hr": true, "12hr": false } } The desired output should be: age - 35 n ...

Exploring the world of AngularJS with nested JSON structures and utilizing ng-repeat

While going through code left behind by a previous team member, I find myself navigating the transition to Angular solo, without anyone around to brainstorm with. This brings me to my question for the community. I am working with JSON data that contains t ...

Discovering the smallest and largest values in an object literal using JavaScript

I am looking to extract the minimum value from an object literal and utilize it in AngularJS, as shown below: scope.data = { 'studentName' : "Anand", 'socialStudies' : "98", 'english' : "90", 'math' ...