Pausing execution
When you use Office Scripts to write a program that depends on external processes, you may sometimes want to pause processing for a certain amount of time.
This article explains how to use Office Scripts to implement a wait for a specified number of seconds.
About asynchronous processing
Section titled “About asynchronous processing”To implement a wait, we use an asynchronous function with async/await.
For details on asynchronous functions, see the following page.
Implement asynchronous processingThis article gives an overview of asynchronous processing with async/await and with Promise, and explains how to implement it in Office Scripts, with sample code.
Define a function that waits for a specified number of seconds
Section titled “Define a function that waits for a specified number of seconds”Define a function that returns a Promise object that completes after the specified time (in milliseconds) has passed.
/** * @param ms Time to wait (in milliseconds) */function wait(ms: number) { return new Promise<void>((resolve) => setTimeout(() => resolve(), ms));}Sample code
Section titled “Sample code”Add async to the main function, and call the wait function defined above with await.
async function main(workbook: ExcelScript.Workbook) { console.log('Processing started');
await wait(1000);
console.log('1 second has passed');}Loops (iteration)Explains how to implement loops in Office Scripts using for statements, while statements, and forEach, with sample code.