Skip to content

Commit

Permalink
post: addendum
Browse files Browse the repository at this point in the history
  • Loading branch information
jpoehnelt committed Jul 8, 2024
1 parent 75efbc2 commit 0d875c7
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/posts/apps-script-async-await.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!

0 comments on commit 0d875c7

Please sign in to comment.