0

I have in NodeJS a variable that updates every second. I want to monitor it to see if it turns below a certain threshold (e.g. 1000).

If it does go below the threshold, it should wait 5 seconds and monitor if the variable goes back above again. If not, it should return a function. If it does go above, it can stop the times and start monitoring again.

Can't get any code to work.

Not sure if the code below is even in the right direction..!

var waitedSoFar = 0;
var imageDisplayed = CheckIfImageIsDisplayed(); //this function is where you check the condition

while(waitedSoFar < 5000)
{
   imageDisplayed = CheckIfImageIsDisplayed();
   if(imageDisplayed)
   {
      //success here
      break;
   }
   waitedSoFar += 100;
   Thread.Sleep(100);
}
if(!imageDisplayed)
{
    //failed, do something here about that.
}

1 Answers1

0

You could have a function that observe and wrap this variable that change so often. Something as simple as

function observeValue(initialValue) {
  let value = initialValue
  let clearEffects = []
  let subscribers = []
  return {
    value: () => value,
    change(val) {
      clearEffects.forEach(oldEffect => oldEffect && oldEffect())
      value = val
      clearEffects = subscribers.map(subscriber => subscriber(value))
    },
    subscribe(listener) {
      subscribers.push(listener)
    }
  }
}

is generic enough. The function returns three methods:

  • one to get the current value
  • one to change the value
  • on to subscribe on every value change

I would suggest to leverage the last one to monitor and trigger any side effects.

You can use it like this:

const monitor = observeValue(true)

monitor.subscribe((value) => {
  if (value !== false) {
    return
  }

  const timeout = setTimeout(() => {
    console.log('value was false for five seconds')
  }, 5000)

  return () => {
    clearTimeout(timeout)
  }
})

and somewhere else you can change the value with

monitor.change(false)
Federkun
  • 36,084
  • 8
  • 78
  • 90