Brian Bennett Brian Bennett - 1 month ago 21
Javascript Question

Automatically update Google Apps Script webapp

I have a Google web app displaying an HTML dashboard with data pulled in via AJAX. The Spreadsheet is populated using a Google Form and I'd like the data (mock election results) to be updated every 10 seconds or so as votes come in so teachers can see live results.

Here's the relevant portion of the app:

code.gs

function getData() {
var sheet = ss.getSheets()[3];
var data = sheet.getDataRange().getValues();
Logger.log(data);
return JSON.stringify(data);
}

function doGet() {
return HtmlService
.createTemplateFromFile("index")
.evaluate();
}


HTML template

function popularVote(data) {
var getDivs = document.getElementsByClassName("percent");
var data = JSON.parse(data);

for(var j=0;j<getDivs.length;j++) {
getDivs[j].textContent = ((data[j][1]/data[j][2]) * 100).toFixed(1) + "%";
}
}
google.script.run.withSuccessHandler(popularVote).getData();

<div class="card" id="popular">
<div class="cand" id="cand1">
<h2>Candidate:</h2><span class="percent">Loading...</span>
</div>
<div class="cand" id="cand2">
<h2>Candidate:</h2><span class="percent">Loading...</span>
</div>
<div class="cand" id="cand3">
<h2>Candidate:</h2><span class="percent">Loading...</span>
</div>
</div>


What I can't figure it out is what actually pulls the data. Is the the success handler polling the server? Or is it the client-side script? Where should I include
Utilities.sleep
or similar?

Answer

It seems like this line is getting the data from the spreadsheet:

google.script.run.withSuccessHandler(popularVote).getData();

You could try wrapping this line in setInterval so that it is called every ten seconds:

setInterval(function(){ 
 google.script.run.withSuccessHandler(popularVote).getData(); 
 }, 10000);

There also may be a Google Apps Script equivalent for setInterval.