diff --git a/src/posts/apps-script-async-await.md b/src/posts/apps-script-async-await.md index 7ea9f4bf..d4869c2d 100644 --- a/src/posts/apps-script-async-await.md +++ b/src/posts/apps-script-async-await.md @@ -135,6 +135,46 @@ This output works as expected: So, it is clear that the WebAssembly API is running asynchronously and not blocking the task queue. +## Addendum: `setTimeout` and `Utilities.sleep` + +The functions `setTimeout` and `setInterval` are typically used to create asynchronous behavior in JavaScript. However, in Apps Script, these functions are not defined and will result in `ReferenceError: setTimeout is not defined`. + +It may be tempting to use `Utilities.sleep()` to create asynchronous behavior to recreate `setTimeout`, but this function is synchronous and will block the task queue. + +```javascript +new Promise((resolve, reject) => { + console.log("start"); + Utilities.sleep(2000); + console.log("end"); + resolve(); + }).then(() => console.log("done")); +console.log("next"); +``` + +This will output the following: + +```sh +3:20:21 PM Notice Execution started +3:20:22 PM Info start +3:20:24 PM Info end +3:20:24 PM Info next < this is printed after the sleep!!! +3:20:24 PM Info done +3:20:24 PM Notice Execution completed +``` + +If this was asynchronous, the `next` would be printed before the `end`. + +Interestingly, if you use `async`/`await`, the output changes to: + +```sh +3:22:37 PM Notice Execution started +3:22:38 PM Info start +3:22:40 PM Info end +3:22:40 PM Info done +3:22:40 PM Info next < this is printed after the sleep!!! +3:22:40 PM Notice Execution completed +``` + ## Conclusion The topic here is a bit esoteric, but as you attempt to push the limits of what is possible in Apps Script, it is good to know that you can use Promises, async and await in your code. I hope to share much more in the future on WebAssembly and other advanced topics in Apps Script! \ No newline at end of file