Home > Enterprise >  Execute code only if condition matches and check for value in regular intervals in Typescript
Execute code only if condition matches and check for value in regular intervals in Typescript

Time:01-18

I have to execute some piece of code only if the value of some variable matches some value. Also I have to keep on checking for the value of the variable at regular intervals and even if after sometime(maxWaitTime), the value is not equal, then I have to stop checking for the value of the variable and send a message to the user.

My present code is as follows:

const intervalId = setInterval(function () {
  const localStorageArray = JSON.parse(
    localStorage.getItem('myArray') || '[]',
  );

  if (
    !localStorageArray ||
    (localStorageArray && localStorageArray[0] === myCurrentVal)
  ) {
    clearInterval(intervalId);
  }
}, 1000);

// other code

Here the other code is getting executed without waiting for the if condition in setInterval. Is it because setInterval will not be in the call stack? Please correct me if I am wrong. I have to execute the other code above inside the if condition of setInterval or else stop execution (be inside the interval) until the maxWaitTime is reached. How can I implement this?

CodePudding user response:

if (!localStorageArray) is never true so you can remove it.

Try this

let localStorageArray = JSON.parse(localStorage.getItem('myArray') || '[]');
window.addEventListener('storage', (event) => { localStorageArray = JSON.parse(localStorage.getItem('myArray') || '[]') });
const count = Math.max(maxWaitTime / 1000)
const intervalId = setInterval(() => {
  const found = localStorageArray.findIndex(myCurrentVal) === 0;
  const done = --count <= 0;
  if (found || done) clearInterval(intervalId);
  if (found) processOtherCode();
  else alert('I give up');
}, 1000);
  • Related