Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required module does not update when the variable inside that module changes

I have a javascript file and in it I require another file that has a variable that changes.

main.js

let num = require("./extra").num

extra.js

let num = 5;

setInterval(() => {
  if (num > 0) {
    num--;
  }
  console.log(num);
}, 1000);

module.exports = {
  num
};

Now in the main.js file that variable num is always 5 and never changes. What do I need to do to get it updated all the time?

Note: I'm declaring the variable in main.js AFTER the variable changes so it shouldnt't be 5

like image 828
Pecius Avatar asked Sep 12 '25 16:09

Pecius


1 Answers

This will work:

in extra.js:

let num = 5;

setInterval(() => {
  if (num > 0) {
    num--;
  }
  console.log("in extra: " + num);
}, 1000);

module.exports = {
  getNum: function() {
    return num;
  }
};

in main.js:

let num = require('./extra').getNum();
console.log("initial value is: " + num);

setInterval(() => {
  let num = require('./extra').getNum();
  console.log("in main loop: " + num);
}, 1000);

Since the print statements in main.js output every second, you'll notice that every new call of require('./extra').getNum() will get the newly decremented value.

like image 178
natn2323 Avatar answered Sep 14 '25 07:09

natn2323