Search code examples
google-apps-scriptgoogle-sheetsweb-applicationstracking

How to make Google Script wait 3 seconds between two functions? The 2 functions are in 1 button


ABOUT: I made a Google Script Web App for tracking packages for our freight company. The database is on Google Sheets, with two sheets named "Tracker" and "Program" to automatically track packages.

PROCESS:

  1. On the web app I enter the Tracking Number
  2. On click, this gets sent to the Tracker sheet
  3. Program sheet gets the tracking number from Tracker sheet, and takes 2-3 seconds to get data
  4. The data from Program sheet (which only has 1 row of data - only the relevant data) gets sent back to the web app for the client to view

MY PROBLEM: I need to have Steps 2 & 4 execute with 1 click of a button. Right now, it can do so if I fill up the form twice (which is a hassle for the clients).

QUESTION: Is there a way I can execute Step 2 first, then Google Script waits 3 seconds before executing Step 4? In just 1 click of the button

// STEP 2 where tracking number gets sent to Sheets
function sendTracking(formObject) {
  google.script.run.processForm(formObject);
  document.getElementById("myForm");
}

// STEP 4 where tracking status is returned from Sheets to Web App
function trackingInfo(formObject) {
  google.script.run.withSuccessHandler(createTable).processReturnForm(formObject);
  document.getElementById("myForm").reset();
}

WHAT I'VE TRIED: All these returned blank -- I've placed all of them in between the two functions of Step 2 & 4. I'm not sure if I'm just entering them wrong or if they really don't work with my functions.

  • SpreadsheetApp.flush();
  • Utilities.sleep(3000)
  • LockService.getScriptLock(); lock.waitLock();

// COMBINED: Process STEP 2 & 4
function handleFormSubmit(formObject) {
  sendTracking(formObject); // THIS IS STEP 2
  // codes above inserted here
  trackingInfo(formObject); // THIS IS STEP 4
}

OTHER RELEVANT CODES:

The code behind Step 2:

function processForm(formObject) {
  var url = "URL";
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Tracker");

ws.getRange('D3').setValue(formObject.trackingNumber);
}

The code behind Step 4:

function processReturnForm(formObject){  
  var result = "";
  if(formObject.trackingNumber){//Execute if form passes search text
  result = search(formObject.trackingNumber);
  }
return result;
}

Solution

  • Place it at the end of processForm or at the beginning of your SuccessHandler.

    As I answered in your previous question. The execution sequence is not ensured in your code. Please first fix that.

    Utilities.sleep(3000);
    

    Reference:

    sleep(milliseconds)