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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With