如何使用Utilities.sleep()函数 [英] How to use Utilities.sleep() function

查看:134
本文介绍了如何使用Utilities.sleep()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Utilities.sleep()函数的确切用途是什么?我们应该在函数调用还是API调用之间使用它?

我使用 Utilities.sleep(1000)中间函数调用,是不是?它会减慢执行时间吗?

解决方案

Utilities.sleep(毫秒)在程序执行过程中创建了一个暂停在你要求的毫秒数内不做任何事情。
它肯定会减慢你的整个过程,你不应该在函数调用之间使用它。
虽然有一些例外,但至少我知道的一个例外:在SpreadsheetApp中,当您要删除多个工作表时,您可以在每次删除之间添加几百毫秒以允许正常的脚本执行(但此是针对此特定方法的已知问题的解决方法)。我在创建电子表格中的许多工作表时也必须使用它,以避免浏览器在执行后需要'刷新'。



以下是一个示例:

 函数delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet = ss.getNumSheets(); //检查电子表格中
的数量(pa = numbofsheet-1; pa> 0; - pa){
ss.setActiveSheet (ss.getSheets()[PA]);
var newSheet = ss.deleteActiveSheet(); //删除最后一张开始的表单
Utilities.sleep(200); //在循环中暂停200毫秒

ss.setActiveSheet(ss.getSheets()[0] ); //返回第一张表作为活动表(在'list'函数中有用)
}


What is the exact use of Utilities.sleep() function? Should we use it between function calls or API calls?

I use the Utilities.sleep(1000) in-between function calls, is it right? Will it slow down the execution time?

解决方案

Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.

Here is an example :

function delsheets(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
  for (pa=numbofsheet-1;pa>0;--pa){ 
    ss.setActiveSheet(ss.getSheets()[pa]);
    var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
    Utilities.sleep(200);// pause in the loop for 200 milliseconds
  }
  ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}

这篇关于如何使用Utilities.sleep()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆