skip to Main Content
const navTimeout = new Promise((resolve, reject) => {
    setInterval(async () => {
        try {
            await workbook.xlsx.readFile("variables.xlsx")
            const sheet = workbook.getWorksheet(1)
            if(sheet.getCell('B13').value === "D")
                return resolve(true)
        } catch (error) {
            console.log("Workbook being used")
        }
    }, 5000)
})

I have the following piece of code. So my doubt is once the promise gets fulfilled and the resolve is done do I need to call clearTimeout() or it will automatically stop executing? I just don’t want it to occupy any pc resources.

2

Answers


  1. It will not automatically stop executing, you have to stop it by clearing it manually:

    const navTimeout = new Promise((resolve, reject) => {
      const intervalId = setInterval(async () => {
        try {
          await workbook.xlsx.readFile("variables.xlsx");
          const sheet = workbook.getWorksheet(1);
          if (sheet.getCell('B13').value === "D") {
            clearInterval(intervalId); //stop it here
            resolve(true);
          }
        } catch (error) {
          console.log("Workbook being used");
        }
      }, 5000);
    });
    
    Login or Signup to reply.
  2. You’re using setInterval to execute a function every 5 seconds. However, it’s important to note that setInterval will continue to execute the function indefinitely until it is explicitly stopped.

    To stop the execution of the interval and release the resources associated with it, you need to call clearInterval. In your case, since you’re using setInterval within a promise, you would need to store the interval ID returned by setInterval and later use it to clear the interval when the promise is resolved.

    Here’s an example of how you can modify your code to stop the interval execution after the promise is resolved:

    const navTimeout = new Promise((resolve, reject) => {
        const intervalId = setInterval(async () => {
            try {
                await workbook.xlsx.readFile("variables.xlsx")
                const sheet = workbook.getWorksheet(1)
                if (sheet.getCell('B13').value === "D") {
                    clearInterval(intervalId); // Stop the interval execution
                    resolve(true);
                }
            } catch (error) {
                console.log("Workbook being used");
            }
        }, 5000);
    });
    

    By calling clearInterval(intervalId) inside the if block, you ensure that the interval execution is stopped as soon as the desired condition is met and the promise is resolved. This will prevent the interval from continuing indefinitely and occupying unnecessary resources on your computer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search