有没有一种方法可以在Google Apps脚本中创建一个for循环,该循环每秒增加一分钟?

时间:2020-07-24 20:12:24

标签: javascript google-apps-script timer spreadsheet google-docs-api

最近,我一直在从事一个项目,该项目将数据从google doc实时流式传输到google电子表格。我一直在使用Apps Script API,并创建了一个周期,该周期使用基于时间的触发器方法每分钟更新一次。我也知道,Apps Script不允许for循环持续超过5分钟。因此,我的理论是,触发器每分钟调用一次的函数可以有一个运行约一分钟的循环。问题是,我无法在一秒钟内(每秒甚至每2或3秒一次)运行一次函数。下面的代码是我用来创建此循环的代码,但无法正常工作。它将以极快的速度运行在一两秒之内,或者将持续运行并且永不停止。

function myfunction() {
  let start = new Date().getTime()
  const limit = 60;
  let timeEllapsed = 0
  
  for(i=0; i < 60; i++) {
    let start = new Date().getTime()
    while(true){
     if(start > new Date().getTime + 1000) {
      Logger.log(timeEllapsed)  
      timeEllapsed += 1
      break
   }
  }
}
}

如何解决此问题,以便for循环每秒仅重复一次,并且脚本将在60秒后完成运行?

2 个答案:

答案 0 :(得分:2)

Apps脚本具有sleep()方法,该方法将暂停代码:

function myfunction() {
  let start = 0;
  var timeEllapsed = 0;
  
  const limit = 60000;
  const increment = 1000;//1000 milliseconds is 1 second
  
  while(timeEllapsed < limit){
    timeEllapsed += increment;
    Utilities.sleep(1000);//Wait for 1 second
  }
  
  Logger.log(timeEllapsed);
}

答案 1 :(得分:2)

60秒计时器:

HTML:

[Location] 
[Data]

GAS:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <title><b>Output Folder</b></title>
  </head>
  <script>
    var t=0;
    var id='';
    function increment() {
      t+=1;
      check(t);
      document.getElementById('txt1').value=t;
      google.script.run.onSecond(t);//Calls a server side function
    }
    function reset() {
      clearInterval(id);
      t=0;
    }
    function start() {
      id=setInterval(increment,1000);
    }
    function check(t) {
      if(t>=59) {
        reset();
      }
    }
  </script>
  <body>
    <input type="text" id="txt1" />
    <br /><input type="button" value="Start" onclick="start();" />
    <br /><input type="button" value="Stop" onclick="reset();" />
  </body>
</html>