I'm trying to listen for a variable change in node.js
I've tried doing it myself like this:
async function sleep(timeout){
await new Promise(r => setTimeout(r,timeout));
}
let update=0;
let variable=1;
async function latest_value(){
while(update!=1){await sleep(500);}
return variable;
}
async function set_var(value){
update=1;
variable=value;
}
(async ()=>{
console.log(await latest_value());
})();
set_var(2);
but it's not instantaneous, more of a hack of checking every 0.5secs
so can someone please tell me a way to achieve the desired results efficiently?
Maybe proxy is a way to go?
Note
The above code is just an example of what I need, please do not suggest a ways to bypass the issue
Edit
Also I'm not looking JUST for variable change like this, I need the function to wait on it as well
I've looked into proxy & setters but as far as I could tell they INVOKE a function when value is changed, I need a function that WAITS till the value is changed
This person has the right idea, Look at the 4th comment for reference