Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

How do i stop Timeout from running if condition changes/updates in node js ?

By M.K. Verma · 2 May 2022

How do i stop Timeout from running if condition changes/updates in node js ?

This works perfectly in browser console (you can launch the snippet), should work in Node as well:

 

// Object of your condition
const isEnd = {
  _value: false, // this is the value of the condition
  valueListener: function(val) {}, // defining a generic listener

  // getter
  get value() {
    return this._value;
  },

  // setter
  set value(val) {
    this._value = val;
    this.valueListener(val); // when changing the value, the function valueListener is called with the new value set
  },

  // method to pass an actual listener function to valueListener property
  listenTo: function(listener) {
    this.valueListener = listener;
  }
};

console.log("START: isEnd has a value of: " + isEnd.value);


// timer of 20 seconds
const timer = setTimeout(() => {
  console.log('Timer expired');
}, 20000)

// you subscribe to the isEnd.value change, passing an actual listener function
// this function should contain the logic to execute
// based on the new condition value
// (like clearing the timer)
isEnd.listenTo(function(val) {
  console.log('new value for isEnd is now: ' + val);

  if (val === true) {
    if (timer) {
      clearTimeout(timer);
      console.log('timer cleared!');
    }
  }

  if (val === false) {
    console.log('HEY... false again!');
  }
})

// timer of 5 seconds that simulates
// the condition changing after 5 seconds
setTimeout(function() {
  isEnd.value = true;
}, 5000)

// timer of 10 seconds that simulates
// the condition changing after
// another 5 seconds
setTimeout(function() {
  isEnd.value = false;
}, 10000)