I am trying to use google.script.run, the asynchronous client-side JavaScript API provided by Google Scripts within a while loop. I understand that calls to google.script.run are asynchronous so I even tried using a global variable 'window.i' for loop iterations.
Unfortunitely window.i++ never happens and the browser freezes when I run this code.
Here's the code snippet that I am struggling with:
var iterations = 5;
window.i = 0;
while (window.i < iterations) {
google.script.run
.withSuccessHandler(function(){
window.i++;
})
.sendNow();
}
Is there any way I can increment the loop variable on success callback?
Use the success handler to send the next request. Dont use a while loop.
//these dont have to be global
var i = 0;
var iterations = 5;
function send() {
google.script.run
.withSuccessHandler(function() {
i++;
if (i < iterations) {
send();
}
})
.sendNow();
}