Trouble with Excel Office Script setInterval functionality

Trying to automatically recalculate an Excel worksheet every second using Office Script. Unfortunately, my initial approach did not succeed.

function sendUpdate(sheet: ExcelScript.Worksheet) {
  console.log('hi');
  sheet.calculate(true);
}

function updateSheet(workbook: ExcelScript.Workbook) {
    let activeSheet = workbook.getActiveWorksheet();
    setInterval(sendUpdate, 1000, activeSheet);
}

No output is displayed on the console and the recalculation process does not occur as expected.

Answer №1

One of my contributions includes working on the Office Script runtime.

In general, Office Scripts are meant to carry out a series of steps and then finish. They are not intended to run continuously in the background.

As it stands, using `setInterval` will not function properly due to the way Office Scripts operate. Furthermore, only one Office Script can run at any given time.

I would advise against trying to sustain an Office Script running perpetually since the runtime does not support this behavior.

However,

In the past, I have utilized busy waiting techniques to introduce delays between actions. You can take a look at the `sleep` function provided below:

https://github.com/wandyezj/office-script/blob/main/functions/sleep.ts


function sleep(seconds: number) {

  const millisecondDelay = seconds * 1000
  const start = Date.now()
  let now = Date.now();

  while((now - start) < millisecondDelay) {
    now = Date.now();
    // busy wait
    for (let i = 0; i < 1000; i++){}
  }

}

Answer №2

I am using the sleep function from @wandyezj for my project. Check out the code below.

function sleep(seconds: number) {
    const delayInMilliseconds = seconds * 1000;
    const startTimestamp = Date.now();
    let currentTimestamp = Date.now();

    while ((currentTimestamp - startTimestamp) < delayInMilliseconds) {
        currentTimestamp = Date.now();
        // busy wait
        for (let j = 0; j < 1000; j++) { }
    }
}

async function execute(workbook: ExcelScript.Workbook) {
    let activeSheet = workbook.getActiveWorksheet();
    for (let i = 0; i < 60; i++) {
        await activeSheet.calculate(true);
        sleep(1);
    }
}

Answer №3

While I may not be well-versed in offise-js, based on common principles, it appears that the variable sheet is lacking a proper value during the timer event. To address this issue, consider defining the variable globally (if feasible) or retrieving the sheet within the sendMessage function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for activating multiple CSS animations when scrolling

I am currently working on a project that involves multiple CSS animations. However, I am facing an issue where these animations only occur once when the page initially loads. I would like them to trigger every time the user scrolls past them, regardless of ...

The Javascript modification of an ASP.NET TextBox goes unnoticed

For someone skilled in this area, this task should be a breeze. I have three components: a launch calendar button, a continue button, and a date textbox. When the button is clicked, a JavaScript calendar pops up in a new window. This calendar sets a date ...

Transfer the chosen language from the uib-dropdown language selector to the $scope variable

Here is a HTML template that allows the user to select a language: <div class="btn-group" uib-dropdown> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" uib-dropdown-toggle> ...

Encountering an error while attempting to add class-constructed objects to an array list in React/NextJs: "Unable to add property 0, as the object is

This function contains the code required to generate rows for display in a Material Ui table. class User { constructor(id, name, email, measured, offset, paidAmount, status, home, misc, plane, transport, partner, isCoupon) { thi ...

Several dropdown menus within the same container, working independently of each other

I recently encountered an issue with a drop-down navigation bar. When I have multiple drop-downs and click on one, it opens as expected. However, if I then proceed to click on another drop-down while the first one is already open, both of them remain open ...

Mongoose: CastError occurs when querying with an incorrect ObjectId for a nested object

I have the following schema defined: var Topic = new Schema({ text: String, topicId: String, comments: [{type: Schema.Types.ObjectId, ref:'Comment'}] }); var Comment = new Schema({ text: String }); I am working on a RESTFul API that w ...

What is the best way to modify the CSS of a child element within the context of "$(this)"

On my search results page, each result has an icon to add it to a group. The groups are listed in a hidden UL element on the page with display:none. The issue I'm facing is that when I click on the icon for one result, the UL appears under every sing ...

What could be the reason behind the varying outcomes browsers provide for the JavaScript expression new Date(-105998400000)?

When I use ASP.NET MVC 3 with the default Json serializer, I notice that dates from my JsonResults come back in the format /Date(-105998400000)/. To handle this, I extract the number and create a new Date object with this value. However, I am experiencing ...

Understanding how events propagate in three.js

I am currently working on a scene that consists of multiple objects. To manipulate the selected object, I am using an orthographic camera controller. Specifically, I want to rotate the object with the mouse by pressing shiftKey + 1 (rotation around its own ...

Issues with AJAX functionality not operating properly in a web form, leading to automatic redirection to a PHP script. Possible solutions and troubleshooting

I have a feature on my web application that allows users to add their skills by clicking the "Add a Skill" button. It was working fine until I tried to incorporate something new. The issue is that when I click the "Add a Skill" button, it acts as though it ...

Creating an instance of a class using a class decorator, with or without the 'new'

Seeking alternatives to creating class instances without using the new keyword in TypeScript, I came across this excellent solution that works seamlessly in JavaScript. The code found in the repository mentioned https://github.com/digital-flowers/classy- ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

The expiration of the Gitlab CI/CD cache leads to the failure of the build process

I have an AWS CDK application in TypeScript and a simple GitLab CI/CD pipeline with 2 stages for deployment: image: node:latest stages: - dependencies - deploy dependencies: stage: dependencies only: refs: - master changes: - ...

Are the fromPromise and toPromise functions in Rxjs resource-intensive?

Within my TypeScript application, I have come to a stage where one of my methods performs multiple operations with fromPromise and toPromise: myMethod(...): Promise<string> { return fromPromise(this.someService1.someMethod1(...)).pipe( m ...

Performing three consecutive Ajax requests in a Rails application

Recently, I developed a custom admin system for a local gym to manage payments, attendance, mailing, sales, and more. While everything is functioning smoothly, there seems to be an issue with the attendance feature. Occasionally, when taking attendance, an ...

What is the best way to showcase a collection of inherited objects in Angular?

How can I efficiently display a list of various objects that inherit from the same abstract class in an Angular application? What is considered optimal practice for accomplishing this task? Consider the following basic model: abstract class Vehicle { ...

Tips for combining HTML and JavaScript on a WordPress site

As a WordPress developer who is still learning the ropes, I have come across a challenge with embedding html and JavaScript onto a page. Currently, I am in the process of redesigning a company website and one of the tasks involves integrating a calculator ...

Samsung Galaxy S7 can interpret alphabetical parameters as numbers in a link sent via SMS

When trying to open a text message with a new message on my website using a link, I encountered an issue specifically with the Galaxy S7. The following code works on most Android phones: sms:5555555555?body=JOIN However, on the Galaxy S7, the "?body=JOIN ...

Navigating through the Angular Upgrade Roadmap: Transitioning from 5.0 to 6

As per the instructions found in this helpful guide, I executed rxjs-5-to-6-migrate -p src/tsconfig.app.json. However, an error is appearing. All previous steps were completed successfully without any issues. Any suggestions on how to resolve this? Please ...

Retrieve the expansive offset label for a time zone utilizing moment-timezone

The luxon library enhances the ability to retrieve the offsetNameLong based on the timezone ianaName, which gives a localized translated zone name. For example: DateTime.local().setLocale("en-US").setZone("America/Los_Angeles").offsetNa ...