I use Google Script in my Google Sheets, to help me shortening url. Below is my script:
function ShortURL(longUrl) {
const url = "http://example.com/api/url/add";
const params = {
method: "post",
headers: { Authorization: "Token MYTOKEN" },
contentType: "application/json",
payload: JSON.stringify({
"url": longUrl
})
};
const res = UrlFetchApp.fetch(url, params);
var shortUrl = JSON.parse(res.getContentText()).short;
Logger.log(shortUrl);
return shortUrl;}
But I got error when I run it in my google sheets. It just fetch below 100 urls The error message is:
Exception: Service invoked too many times for one day: urlfetch. (line 11).
I read that I can use cache to avoid error but not sure how to use it in my code above
How can I use cache to enhance my script above?
I search in stackoverflow, found some answer here but, since I have no idea to implement it in my script, I still got confuse.
I search that we can use Utilities.sleep() to slow down the script, is that possible?
Got the answer:
So I can use function below:
const min = 1; // milliseconds in one minute
const max = 20000; // milliseconds in 20s since custom function max run time 30s
const waitTime = Math.floor(Math.random() * (max - min + 1) ) + min;
Utilities.sleep(waitTime);
so my code become:
function ShortURL(longUrl) {
const url = "http://example.com/api/url/add";
const params = {
method: "post",
headers: { Authorization: "Token MYTOKEN" },
contentType: "application/json",
payload: JSON.stringify({
"url": longUrl
})
};
const res = UrlFetchApp.fetch(url, params);
var shortUrl = JSON.parse(res.getContentText()).short;
Logger.log(shortUrl);
const min = 1; // milliseconds in one minute
const max = 20000; // milliseconds in 20s since custom function max run time 30s
const waitTime = Math.floor(Math.random() * (max - min + 1) ) + min;
Utilities.sleep(waitTime);
return shortUrl;}
And It proven
Thank you :)